通过注解@Component方式,applicationContext有时会为null的问题解决方法
来源:互联网 发布:帝国时代2mac 编辑:程序博客网 时间:2024/05/17 03:52
当我们想通过获取Spring的上下文环境ApplicationContext的方法来获取一个指定的类的实例的时候,我们可以采用如下注解的方法:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Component
public class SpringContextHolder implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// TODO Auto-generated method stub
SpringContextHolder.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
public static <T>T getBean(String beanName,Class<T>clazz){
return applicationContext.getBean(beanName, clazz);
}
}
但这种方法有时候依然会报applicationContext为null的错误,这时我们就可以不用注解的方式直接在Spring的配置文件applicationContext.xml中单独配置这个bean并且把他放在包扫描之前,如下:
<context:annotation-config/>
<bean id="springContextHolder" class="com.utstar.sobeyadapter.util.SpringContextHolder"></bean>
<!-- 设置当前项目的根包 -->
<context:component-scan base-package="com." />
这样可以避免项目启动时applicationContext报null的错误。
- 通过注解@Component方式,applicationContext有时会为null的问题解决方法
- AS3 textfield.getCharBoundaries(index) 有时会返回NULL的问题解决方案
- JavaCompiler编译的时候有时会返回NULL
- 为什么通过GetComponent获取的组件,有时修改会无效?
- 通过接口调用方法,接口一直为null的解决方法
- Java中通过为null的引用调用静态方法
- 看寄存代码中的方式时,一定要看到方法的底部 (有时代码会在finally中写东西) 。
- Notification通过Intent传递参数getIntent()为null的问题解决
- Spring通过注解得到的值为null,但getbean()可以得到。
- spring 注解方式得到 applicationContext
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得ApplicationContext的方法
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得ApplicationContext的方法
- ApplicationContext——类注解的配置方式
- 跳到系统相册有时会返回Null的地址处理
- @Component注解的使用
- @component的注解
- MyBatis+Spring在注解@Autowried后通过反射的方式调用方法获取注入的Service或DAO对象为空
- 查询条件有时为空有时有的查询方法
- Java设计模式--享元模式【Flyweight Pattern】
- web应用 tomcat调优
- secureCRT利用 Zmodem 和 TFTP 上传/下载文件
- Picasso使用解析
- Node.js学习笔记(2)——新建简单的node.js模块
- 通过注解@Component方式,applicationContext有时会为null的问题解决方法
- 新文件上传文件到SVN,无法ADD,update等
- android ndk简单配置android.mk
- 在安全组实习的第“一”个月
- 微信支付(公众号支付)微信公众平台开发教程(5)
- html2canvas 下载图片 报网络错误
- ibatis查询数据显示为ASCII码的问题
- java编程思想笔记-并发之死锁
- spring boot学习指南