在写代码的时候经常会碰到需要获取JavaBean的场景,使用Spring 的 @Resource/@Autowired 注入基本能覆盖80% 获取bean 的场景,但是在有的场景下不能使用注入的方式,如:在使用dubbo 的filter 功能时,因为dubbo 的filter不由Spring 管理,所以使用注入的方式会导致注入不成功。
此时,只能从容器中手动的获取Bean,根据不同的情况可以有三种方法,前3种是在Web容器启动起来时使用,第4种方法是在Web容器没启动时使用(如Spring 单元测试)
1.SpringBoot 获取ApplicationContext
@Autowired
ApplicationContext context;
2. 继承ApplicationContextAware 来获取Bean
创建一个类继承ApplicationContextAware
package com.example;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
this.applicationContext = applicationContext;
}
public static ApplicationContext getContext() {
return applicationContext;
}
public static <T> T getBean(String name) {
if (applicationContext == null) {
return null;
}
return (T) applicationContext.getBean(name);
}
}
将ApplicationContextAware 配置进application-context.xml
<bean id="applicationContextUtil" class="com.example.ApplicationContextUtil"/>
在需要的地方获取bean
TestBean testBean = ApplicationContextUtil.getBean("testBean");
3. 使用ContextLoader 获取bean
ApplicationContext app = ContextLoader.getCurrentWebApplicationContext();
TestBean testBean = app.getBean("testBean", TestBean.class);
4. 继承 BeanFactoryAware 获取bean
在单元测试时,像dubbo filter这种场景,只能使用Spring 容器来获取bean了, 示例如下:
创建一个类继承BeanFactoryAware
package com.example;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class SpringBeanFactory implements BeanFactoryAware {
private static BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory factory) throws BeansException {
this.beanFactory = factory;
}
/**
* 根据beanName名字取得bean
* @param name
* @param <T>
* @return
*/
public static <T> T getBean(String name) {
if (beanFactory == null) {
return null;
}
return (T) beanFactory.getBean(name);
}
}
SpringBeanFactory 配置进application-context.xml
<bean id="springBeanFactory" class="com.example.SpringBeanFactory"/>
在需要的地方获取bean
TestBean testBean = SpringBeanFactory.getBean("testBean");