如何在普通的类中获取spring容器中的bean
最常见的情况大概就是有一个类他的属性的是通过spring的配置文件读取的。这样这个类必然要交给Spring容器进行管理。这个时候如果我们在普通类中直接new这个类是不可以拿到的。属性值不会加载成功。
整体思路
封装一个SpringContextUtil来获取bean,然后普通类直接通过这个工具类来从容器中拿bean即可
封装SpringContextUtil
思路就是获取applicationContext
,然后通过applicationContext
的getBean
方法获取容器中的bean
。
那么,applicationContext
从哪里获取呢?
就是通过实现ApplicationContextAware
接口,实现setApplicationContext
方法,然后spring启动的时候会自动调用这个set方法,将applicationContext
加进去,然后就可以用这个工具类做各种操作了!
具体实现代码:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
/**
* @author hc
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextUtil() {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextUtil.applicationContext == null) {
SpringContextUtil.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);
}
public static void publishEvent(ApplicationEvent event) {
if (applicationContext != null) {
applicationContext.publishEvent(event);
}
}
}
使用SpringContextUtil获取bean
这样就可以在任何地方获取spring容器中的bean了
Example bean = SpringContextUtil.getBean(Example.class);
如何在普通的类中获取spring容器中的bean
https://www.powercheng.fun/articles/dfc1f761/