[TOC]

How SpringBoot gets the ApplicationContext

Since I was lazy before, every time I wanted to get a Spring context. I've been using it a lot lately, so I've summarized how to get the Spring context. A total of four acquisition methods are summarized. Public class SpringBeanUtils {private static ApplicationContext ApplicationContext; public static voidsetApplicationContext(ApplicationContext applicationContext){ SpringBeanUtils.applicationContext = applicationContext; }}Copy the code

1. The implementationApplicationContextInitializerinterface

The specific code is as follows:

public class SecondApplicationContextInitializer implements ApplicationContextInitializer {
  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) { SpringBeanUtils.setApplicationContext(applicationContext); }}Copy the code

Once you’ve done this, you need to inject this class into the Spring container in two ways

The first: add 'to this class@Component'Notes the second: In ` resources/meta-inf/spring. Factories ` file to add the following configuration org. Springframework. Context. ApplicationContextInitializer = \ The path of the SecondApplicationContextInitializerCopy the code

Implement the ApplicationListener interface

The specific code is as follows:

public class CustApplicationListener implements ApplicationListener<ApplicationContextEvent> {
  @Override
  public void onApplicationEvent(ApplicationContextEvent event) { SpringBeanUtils.setApplicationContext(event.getApplicationContext()); }}Copy the code

Once you’ve done this, you need to inject this class into the Spring container in two ways

The first: add 'to this class@Component'Notes the second: In ` resources/meta-inf/spring. Factories ` file to add the following configuration org. Springframework. Context. The ApplicationListener = \ The path of the CustApplicationListenerCopy the code

3. Set it in the main method of the startup class

The specific code is as follows

@SpringBootApplication
public class WangMikeSpringApplication {
    public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(WangMikeSpringApplication.class, args); SpringBeanUtils.setApplicationContext(applicationContext); }}Copy the code

4. Implement the ApplicationContextAware interface

The specific code is as follows

@Component
public class SpringBeanUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    public  void setApplicationContext(ApplicationContext applicationContext){ SpringBeanUtils.applicationContext = applicationContext; }}Copy the code