欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot项目获取ApplicationContext

程序员文章站 2022-05-25 10:57:28
...
  1. 直接使用@Autowired注入
    @Autowired
    private ApplicationContext ctx;
    
  2. 实现ApplicationContextAware接口,重写setApplicationContext方法(推荐)
    @Component
    public class ApplicationContextProvider implements ApplicationContextAware{
        
        private ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
        
        public ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    }
    
  3. 继承抽象类ApplicationObjectSupport
    @Component
    public class DashboardServiceConfig extends ApplicationObjectSupport {
    
    	private ApplicationContext ctx;
    
    	@Override
    	protected void initApplicationContext(ApplicationContext context) throws BeansException {
    		super.initApplicationContext(context);
    		ctx = context;
    	}