获取SpringApplicationContext容器上下⽂对象实例
Spring ApplicationContext 容器可以加载配置⽂件中定义的 bean,将所有的 bean 集中在⼀起,当有请求的时候分配 bean。如果说BeanFactory是Spring的⼼脏,那么ApplicationContext就是完整的⾝躯了。ApplicationContext由BeanFactory派⽣⽽来,提供了更多⾯向实际应⽤的功能。另外,它增加了企业所需要的功能,⽐如,从属性⽂件中解析⽂本信息和将事件传递给所指定的。这个容器在 t.ApplicationContext interface 接⼝中定义。
ApplicationContext的初始化和BeanFactory有⼀个重⼤的区别:BeanFactory在初始化容器时,并未实例化Bean,直到第⼀次访问某个Bean时才实例⽬标Bean;⽽ApplicationContext则在初始化应⽤上下⽂时就实例化所有单实例的Bean。因此ApplicationContext的初始化时间会⽐BeanFactory稍长⼀些,不过稍后的调⽤则没有这样的缺陷了。
传统的获取ApplicationContext的⽅式有很多种,下⾯⼩编简单地介绍⼏种常⽤的⽅式!在获取ApplicationContext实例后,就可以调⽤getBean(beanName)返回Bean 了。
为了验证,假设已经构建了Spring Boot项⽬,在包fig中新增测试类。
fig;
import t.annotation.Bean;
import org.springframework.stereotype.Service;
@Service
public class BeanTest {
@Bean
public BeanTest getBeanObj() {
BeanTest bean = new BeanTest();
System.out.println("调⽤⽅法:" + bean);
return bean;
}
}
直接注⼊
@Autowired
private ApplicationContext ctx;
@GetMapping("/getContext")
public String getContext(){
Object bean1 = Bean("getBeanObj");
return String.format(" ctx 打印bean %s", bean1);
}
启动项⽬,可以到⽇志:
2020-06-27 10:50:16.879  INFO 12272 --- [          main] ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2187 ms 调⽤⽅法:fig.BeanTest@3c74aa0d
说明bean已经被注⼊Spring容器,默认bean的名称就是其⽅法名。在浏览器访问函数getContext() 时,会返回bean【getBeanObj】的信息:
ctx 打印fig.BeanTest@3c74aa0d
和启动时⽇志打印的bean 信息⼀致,⽽且,没有执⾏⽅法getBeanObj()。
实现ApplicationContextAware接⼝
创建⼀个实体类并实现ApplicationContextAware接⼝,重写接⼝内的setApplicationContext⽅法来完成获取ApplicationContext实例的⽅法,代码如下所⽰:import org.springframework.beans.BeansException;
import t.ApplicationContext;
import t.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
/**
* 上下⽂对象实例
*/
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
在拿到ApplicationContext对象实例后就可以获取Bean的注⼊实例对象,在ApplicationContextProvider类内简单的实现了⼏个⽅法来获取指定的Bean实例,也可以添加更多的⽅法来完成更多的业务逻辑。
这⾥要注意ApplicationContextProvider类上的@Component注解是不可以去掉的,去掉后Spring就不会⾃动调⽤setApplicationContext⽅法来为我们设置上下⽂实例。我简单的创建了⼀个API,以便测试,效果可以达到要求,代码如下:
@Autowired
private ApplicationContextProvider provider;
@GetMapping("/getContextProd")
public String getContextProd(){
Object bean = Bean("getBeanObj");
return String.format(" ApplicationContextProvider 打印bean %s", bean);
}
在⾃定义AutoConfiguration中获取
有时候我们需要实现⾃定义的Spring starter,并在⾃定义的AutoConfiguration中使⽤ApplicationContext,Spring在初始化AutoConfiguration时会⾃动传⼊ApplicationContext,这时我们就可以使⽤下⾯的⽅式来获取ApplicationContext:
@Configuration
@EnableFeignClients("com.yidian.data.interfaces.client")
public class FeignAutoConfiguration {
FeignAutoConfiguration(ApplicationContext context) {
// 在初始化AutoConfiguration时会⾃动传⼊ApplicationContext
doSomething(context);
}}
启动时获取ApplicationContext
在启动Spring Boot项⽬时,需要调⽤SpringApplication.run()⽅法,⽽run()⽅法的返回值就是ApplicationContext,我们可以把run()⽅法返回的ApplicationContext 对象保存下来,⽅便随时使⽤。下⾯使⽤这个返回⽰例获取Bean⽰例:
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(WienerApplication.class, args);
Object bean1 = Bean("getBeanObj");
System.out.println(String.format("打印bean1 %s", bean1));
bean1 = Bean("getBeanObj");
System.out.println(String.format("打印bean2 %s", bean1));
}
项⽬启动后,在⽇志中可以发现如下三条记录:
调⽤⽅法:fig.BeanTest@3c74aa0d
打印fig.BeanTest@3c74aa0d
打印fig.BeanTest@3c74aa0d
通过WebApplicationContextUtils获取
Spring提供了⼀个⼯具类WebApplicationContextUtils⽤于获取ApplicationContext对象,它是Spring框架基础包中的类,该⽅法必须依赖Servlet容器。RequiredWebApplicationContext(ServletContext sc);
实例化bean的三种方式
测试⽤例:
@GetMapping("/getMyBean")
public String getMyBean(HttpServletRequest request)throws Exception{
ServletContext sc = Session().getServletContext();
ApplicationContext ac = RequiredWebApplicationContext(sc);
BeanTest bean = ac.getBean("getBeanObj");
return String.format(" 当前bean是 %s", bean);
}
关于以上5种获取ApplicationContext上下⽂对象实例的⽅式,⼤家有什么看法,欢迎留⾔讨论,也希望⼤家多多点赞,祝各位⽣活愉快。Reference