Java——ApplicationContext辅助类
1. 需求
在Spring
项目中,经常需要获取Spring容器中的Bean
对象来做反射等功能。常见的做法是实现ApplicationContextAware
接口,如果将这个类做成一个工具类的话,需要@Component
等注解在Spring容器启动时加载,这里提供一种辅助类来实现该功能。
2. 代码实现
ApplicationContextHelper
: 实现ApplicationContextAware
接口
/**
* ApplicationContext辅助类
* @author Tarzan写bug
* @since 2022/10/24
*/
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
}
在项目@Configuration
类或启动类
中初始化辅助类的Bean
@Bean
public ApplicationContextHelper applicationContextHelper() {
return new ApplicationContextHelper();
}
直接使用辅助类来获取Spring容器中的Bean
ApplicationContextHelper.getBean(AppController.class)
3. 总结
这里用到的原理是Java的静态变量在内存中只会保留一份,上述代码收录在https://gitee.com/ouwenrts/tuyere.git
.
世界那么大,感谢遇见,未来可期…
欢迎同频共振的那一部分人
作者公众号:Tarzan写bug