About obtaining applicationContext
The main ones are:
(1) Create a new class to implement the ApplicationContextAware interface
The interface only needs to rewrite the following method, there is the context we want in the parameter, and save it to a static variable.
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("开始保存到静态变量");
ApplicationContextUtil.applicationContext = applicationContext;
}
(2) Add @Component annotations, let spring generate objects (load beans)
Spring will automatically call the setApplicationContext method after the bean is loaded, and the input parameters will be filled in automatically.
(3) Just use static variables later
In fact, this has a premise: static variables can be used only after the bean is loaded.
Are there any exceptions? Yes, it is very common. This static variable is used in the constructor and initialization method of other beans.
What will happen? Null pointer exception.
Let's take a look at the null pointer
The solution is simple, just let the tool bean load first.
https://blog.csdn.net/liuyueyi25/article/details/104970404
Probably it is:
(1) Create a new class (Bean life cycle control) to implement the BeanFactoryAware and InstantiationAwareBeanPostProcessor interfaces. At the same time, add the @Component annotation to let spring generate the object.
- Because the InstantiationAwareBeanPostProcessor interface is implemented, it will be loaded first when spring loads beans through @Component.
(2) In the overridden method, take the initiative to obtain the tool class bean through the beanFactory.getBean() method (obtaining the bean will ensure that the loaded bean is executed). At this time, other beans have not been loaded yet, so they will be loaded first.
- Can be written in setBeanFactory
- You can also write in postProcessAfterInstantiation
@DependsOn and @Autowired choose one
Used to establish bean dependencies and load beans in a chain
Finally look at the effect
Code springboot2, maven project
Lanzous Cloud: https://wws.lanzous.com/i2Uzdjycj5e