Java web项目中,在普通Java 类中手动获取spring bean

问题:
今天在测试写的代码时,发现类中注入的一个bean报空指针异常,显然,这个bean没有注入成功,我看了看那个bean,发现添加service注解了啊,而且别的类使用也没问题,,,于是我仔细看了看自己的那个类,发现我的类不是一个bean,就是一个普通的Java Class类,由于历史原因,还不能改,于是只能手动获取bean了。

解决:
本着为后来者行方便的原则,我写了个获取spring applicationcontext的工具类,如下:

code:

@Component
public class ApplicationContextUtil implements ApplicationContextAware {
	
	 private static ApplicationContext applicationContext;

	@SuppressWarnings("static-access")
	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext = arg0;
	}
	
	/**
	 * 根据bean名称获取bean
	 * @param name
	 * @return
	 */
	public static Object getBean(String name){  
         return applicationContext.getBean(name);  
     }

}

总结:
代码很简单,核心就是实现ApplicationContextAware,获取applicationContext,然后通过applicationContext获取bean。

最后,本博客借鉴了别的前辈的博客,但是现在忘记是哪个了。。。

猜你喜欢

转载自blog.csdn.net/qq_36085004/article/details/85607930