springboot实例化ApplicationContext

2023-03-31 09:58:01 浏览数 (2)

1.直接通过@Resource注解注入

代码语言:javascript复制
@Resource

ApplicationContext applicationContext;

2.实现ApplicationContextAware接口

@Component

代码语言:javascript复制
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        SpringBeanUtils.applicationContext = applicationContext;

    }

    public ApplicationContext getApplicationContext(){

        return applicationContext;

    }

}

3.在启动类main方法中设置

代码语言:javascript复制
ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);

SpringBeanUtils.applicationContext = run;

4.实现ApplicationListener接口

代码语言:javascript复制
@Component

public class CustomApplicationListener implements ApplicationListener<ApplicationContextEvent> {

  @Override

  public void onApplicationEvent(ApplicationContextEvent event) {        

     SpringBeanUtils.applicationContext = event.getApplicationContext();

  }

}

5.实现ApplicationContextInitializer接口

代码语言:javascript复制
@Component

public class CustomApplicationContextInitializer implements ApplicationContextInitializer {

  @Override

  public void initialize(ConfigurableApplicationContext applicationContext) {    

     SpringBeanUtils.applicationContext = applicationContext;

  }

}

0 人点赞