转载请注明出处:https://oldnoop.tech/c/175.html
思想,使用spring提供的ApplicationContextAware接口
编写一个工具类,实现ApplicationContextAware,将ApplicationContext存储起来,
提供获得bean的相关方法
@Component
public class SpringUtils implements ApplicationContextAware{
private static ApplicationContext atx;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.atx = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return atx;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
再需要获得bean的地方
调用SpringUtils.getBean方法就可以了