spring 获取ApplicationContext 对象方法

方式一:实现 ApplicationContextAware 接口或继承其子类

注意加入容器@Component 包扫描

@Component
public class ApplicationContextUtils implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		ApplicationContextUtils.applicationContext=applicationContext;
	}
	public static Object getBean(String beanName){
		return applicationContext.getBean(beanName);
	}
}

方式二:直接注入

@Resource
private ApplicationContext applicationContext;

原文:https://www.jianshu.com/p/02f53c198f3e

你可能感兴趣的:(Spring)