JAVA解决在@autowired,@Resource注入为null的情况
使用SpringMVC或者SSH过程中,有时可能会遇到这么一个问题。就是在一个普通的JAVA类(不是controller也不是action类)中无法注入在spring配置文件中配置的bean。
比如你在一个普通java类想调用某个在spring中配置的service,你会发现不管你用@Resource还是@Autowired注解都无法注入,对象始终是null。
那是因为一般普通的Java类没有被spring代理,自然无法通过spring注入相关的对象。难道这样就不能调用了吗?这里提供下面一个类来解决这个问题:
SpringContextUtil
packagecom.im.utils; importorg.springframework.beans.BeansException; importorg.springframework.beans.factory.NoSuchBeanDefinitionException; importorg.springframework.context.ApplicationContext; importorg.springframework.context.ApplicationContextAware; /** *这个类是为了解决在普通类调用service的问题 * *@ClassNameSpringContextUtil *@Description *@authorkokjuis189155278@qq.com *@date2016-6-12 *@content * */ publicclassSpringContextUtilimplementsApplicationContextAware{ privatestaticApplicationContextapplicationContext;//Spring应用上下文 //下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法 @Override publicvoidsetApplicationContext(ApplicationContextapplicationContext) throwsBeansException{ SpringContextUtil.applicationContext=applicationContext; } publicstaticApplicationContextgetApplicationContext(){ returnapplicationContext; } publicstaticObjectgetBean(Stringname)throwsBeansException{ returnapplicationContext.getBean(name); } publicstaticObjectgetBean(Stringname,ClassrequiredType) throwsBeansException{ returnapplicationContext.getBean(name,requiredType); } publicstaticbooleancontainsBean(Stringname){ returnapplicationContext.containsBean(name); } publicstaticbooleanisSingleton(Stringname) throwsNoSuchBeanDefinitionException{ returnapplicationContext.isSingleton(name); } publicstaticClassgetType(Stringname) throwsNoSuchBeanDefinitionException{ returnapplicationContext.getType(name); } publicstaticString[]getAliases(Stringname) throwsNoSuchBeanDefinitionException{ returnapplicationContext.getAliases(name); } }
然后在spring配置文件中配置一下这个类:
然后通过这个类提供的方法就能正常的获取在spring中托管的bean了,使用很简单:
/** *获取spring托管的redis连接池 */ privateJedisPooljedisPool=(JedisPool)SpringContextUtil.getBean("jedisPool");
补充知识:解决Spring中为静态static的@Resource自动注入失败的问题
在写一个单例模块时,在初始化对象时需要注入静态的参数,导致spring暴出
@Resourceannotationisnotsupportedonstaticfields
可以通过将@Resource写在set方法上,并去除static
以上这篇JAVA解决在@autowired,@Resource注入为null的情况就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。