spring boot 获取ApplicationContext
程序员文章站
2022-05-25 10:57:28
...
https://www.jianshu.com/p/fa5db63a12e5
@Component
@Lazy(false)
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
- 使用:
//通过class获得bean
UserService userService= SpringContext.getBean(UserService.class);
//通过name获得bean
UserService userService= SpringContext.getBean("userService");
//通过name,以及Clazz返回指定的Bean
UserService userService= SpringContext.getBean("userService",UserService.class);
上一篇: ApplicationContext 获取Bean
下一篇: 微博营销中引流方式有哪些
推荐阅读
-
spring_boot pom.xml配置
-
Spring Boot 配置多源的 RabbitMQ
-
Spring Boot邮箱链接注册验证及注册流程
-
Spring Boot整合Lombok的方法详解
-
详解Spring Boot 中使用 Java API 调用 lucene
-
说说在 Spring Boot 中如何配置数据源
-
spring boot Invalid bound statement (not found)
-
Spring获取Web应用根目录的方法 WebSpringlog4jIBMServlet
-
一篇超详细的Spring Boot整合Mybatis文章
-
spring boot项目使用@JsonFormat失效问题的解决