Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Springboot startup extension points

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

In this issue, the editor will bring you what are the Springboot startup extension points. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

1. Background

The core idea of Spring is the container. When the container is refresh, the outside looks calm, but in fact, the inside is a rough sea. Springboot encapsulates Spring and follows the convention greater than configuration, plus the mechanism of automatic assembly. In many cases, we can complete the assembly of a function as long as we refer to a dependency, almost zero configuration.

I like this automatic assembly mechanism so much that I also use this feature when developing my own middleware and common dependency tools. Allow users to access at a minimum cost. If you want to play with autoassembly, you must understand the construction life cycle of spring for bean and the various extension interfaces. Of course, understanding the various life cycles of bean can also help us to deepen our understanding of spring. Business code can also make good use of these extension points to write more beautiful code.

Searching for spring extension points on the Internet, I found that there are few blog posts that are very comprehensive, only some commonly used descriptions of extension points.

In this article, I summarized almost all the extension interfaces of Spring & Springboot, as well as the usage scenarios of each extension point. And sort out a sequential call diagram of bean within the spring from being loaded to the final initialization of all extensible points. So we can also see how bean is loaded into the spring container step by step.

two。 Extensible interface startup call sequence diagram

The following is the calling order of all extensible points in the life cycle of Bean in the spring container that I sorted out, which will be analyzed one by one below.

3.ApplicationContextInitializer

Org.springframework.context.ApplicationContextInitializer

This is the callback interface for initializing ConfigurableApplicationContext before the entire spring container is refreshed. To put it simply, the initialize method of this class is called before the container is refreshed. This point is allowed to be extended by users themselves. Users can do something before the entire spring container is initialized.

The conceivable scenario may be to activate some configuration at the beginning, or to perform dynamic bytecode injection when the class is not yet loaded by the classloader. Search the official account of Java bosom friend, reply to "back-end interview" and send you a treasure book of Java interview questions. Pdf

The expansion method is:

Public class TestApplicationContextInitializer implements ApplicationContextInitializer {@ Override public void initialize (ConfigurableApplicationContext applicationContext) {System.out.println ("[ApplicationContextInitializer]");}}

Because the spring container has not been initialized at this time, there are three ways for your extension to take effect:

Add the springApplication.addInitializers (new TestApplicationContextInitializer ()) statement to the startup class

Profile configuration context.initializer.classes=com.example.demo.TestApplicationContextInitializer

Spring SPI extension, adding org.springframework.context.ApplicationContextInitializer=com.example.demo.TestApplicationContextInitializer to spring.factories

4.BeanDefinitionRegistryPostProcessor

Org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor

This interface is executed after reading the beanDefinition in the project, providing a supplementary extension point

Usage scenario: you can dynamically register your own beanDefinition here, and you can load bean outside of classpath

The expansion method is:

Public class TestBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {@ Override public void postProcessBeanDefinitionRegistry (BeanDefinitionRegistry registry) throws BeansException {System.out.println ("[BeanDefinitionRegistryPostProcessor] postProcessBeanDefinitionRegistry");} @ Override public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println ("[BeanDefinitionRegistryPostProcessor] postProcessBeanFactory");}}

5.BeanFactoryPostProcessor

Org.springframework.beans.factory.config.BeanFactoryPostProcessor

This interface is an extension of beanFactory and is called after spring reads the beanDefinition information and before instantiating the bean.

At this point, the user can implement the extension interface to handle some things from the line, such as modifying the meta-information of the registered beanDefinition.

The expansion method is:

Public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {@ Override public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println ("[BeanFactoryPostProcessor]");}}

6.InstantiationAwareBeanPostProcessor

Org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor

This API inherits the BeanPostProcess interface. The differences are as follows:

The BeanPostProcess interface is extended only in the initialization phase of bean (before and after the injection of spring context), while the InstantiationAwareBeanPostProcessor interface adds three methods on this basis, adding the extensible scope to the instantiation phase and attribute injection phase.

The main extension points of this class have the following five methods, mainly in the two major phases of the bean life cycle: the instantiation phase and the initialization phase, which are described together as follows:

PostProcessBeforeInstantiation: before instantiating bean, it is equivalent to before the bean of new

PostProcessAfterInstantiation: after instantiating bean, it is equivalent to the bean of new.

PostProcessPropertyValues:bean has been instantiated and triggered in the stage of attribute injection. Annotation principles such as @ Autowired,@Resource are implemented based on this method.

PostProcessBeforeInitialization: before initializing bean, it is equivalent to injecting bean into the spring context

PostProcessAfterInitialization: after initializing bean, it is equivalent to injecting bean into the spring context

Usage scenario: this extension point is very useful and can take advantage of this feature in both writing middleware and business. For example, the bean that implements a certain type of interface is collected in each lifetime, or a certain type of bean is uniformly set, and so on.

The expansion method is:

Public class TestInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {@ Override public Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException {System.out.println ("[TestInstantiationAwareBeanPostProcessor] before initialization" + beanName); return bean;} @ Override public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException {System.out.println ("[TestInstantiationAwareBeanPostProcessor] after initialization" + beanName); return bean @ Override public Object postProcessBeforeInstantiation (Class beanClass, String beanName) throws BeansException {System.out.println ("[TestInstantiationAwareBeanPostProcessor] before instantiation" + beanName); return null;} @ Override public boolean postProcessAfterInstantiation (Object bean, String beanName) throws BeansException {System.out.println ("[TestInstantiationAwareBeanPostProcessor] after instantiation" + beanName); return true } @ Override public PropertyValues postProcessPropertyValues (PropertyValues pvs, PropertyDescriptor [] pds, Object bean, String beanName) throws BeansException {System.out.println ("[TestInstantiationAwareBeanPostProcessor] postProcessPropertyValues" + beanName); return pvs;}

7.SmartInstantiationAwareBeanPostProcessor

Org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor

The extension interface has three trigger point methods:

PredictBeanType: this trigger point occurs before postProcessBeforeInstantiation (it is not marked on the figure, because it is generally not necessary to extend this point). This method is used to predict the type of Bean and return the first successful Class type. If you cannot predict and return null; when you call BeanFactory.getType (name), call this callback method to determine the type information when you cannot get the bean type information through the name of bean.

DetermineCandidateConstructors: this trigger point occurs after the postProcessBeforeInstantiation and is used to determine the constructor of the bean, returning a list of all the constructors for the bean. The user can extend this point to customize and select the appropriate constructor to instantiate the bean.

GetEarlyBeanReference: this trigger point occurs after postProcessAfterInstantiation. When there is a cyclic dependency scenario, when the bean is instantiated, the callback method will be exposed in advance for post-processing of bean instantiation in order to prevent circular dependency. This method is triggered in a callback method that is exposed in advance.

The expansion method is:

Public class TestSmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {@ Override public Class predictBeanType (Class beanClass, String beanName) throws BeansException {System.out.println ("[TestSmartInstantiationAwareBeanPostProcessor] predictBeanType" + beanName); return beanClass;} @ Override public Constructor [] determineCandidateConstructors (Class beanClass, String beanName) throws BeansException {System.out.println ("[TestSmartInstantiationAwareBeanPostProcessor] determineCandidateConstructors" + beanName); return null } @ Override public Object getEarlyBeanReference (Object bean, String beanName) throws BeansException {System.out.println ("[TestSmartInstantiationAwareBeanPostProcessor] getEarlyBeanReference" + beanName); return bean;}}

8.BeanFactoryAware

Org.springframework.beans.factory.BeanFactoryAware

This class has only one trigger point, which occurs after the instantiation of bean and before the injection of properties, that is, before Setter. The extension point method of this class is setBeanFactory, and you can get the property BeanFactory.

The usage scenario is that you can get the BeanFactory after the bean is instantiated, but before it is initialized, at this time, you can make special customizations for each bean. Or you can take the BeanFactory to cache and use it later.

The expansion method is:

Public class TestBeanFactoryAware implements BeanFactoryAware {@ Override public void setBeanFactory (BeanFactory beanFactory) throws BeansException {System.out.println ("[TestBeanFactoryAware]" + beanFactory.getBean (TestBeanFactoryAware.class) .getClass () .getSimpleName ());}}

9.ApplicationContextAwareProcessor

Org.springframework.context.support.ApplicationContextAwareProcessor

The class itself does not have an extension point, but there are six extension points within the class that can be implemented, which are triggered after bean instantiation and before initialization

As you can see, this class is used to execute various driver interfaces. After the bean is instantiated and the attributes are populated, the variables of the corresponding container are obtained by executing the extended interface marked in the red box above. So it should be said that there are six extension points here, so let's put it together.

EnvironmentAware: an extension class used to get EnviromentAware. This variable is very useful to get all the parameters in the system. Of course, I don't think it is necessary to extend this Aware, because the internal spring can be obtained directly by injection.

EmbeddedValueResolverAware: an extension class used to get StringValueResolver. StringValueResolver is used to obtain variables of properties based on String type. Generally, we use @ Value to obtain variables. If you implement this Aware interface, cache StringValueResolver, and use this class to get variables of type String, the effect is the same.

ResourceLoaderAware: an extension class used to get ResourceLoader. ResourceLoader can be used to get all resource objects in classpath. You can extend this class to get ResourceLoader objects.

ApplicationEventPublisherAware: an extension class used to get ApplicationEventPublisher. ApplicationEventPublisher can be used to publish events for common use in conjunction with ApplicationListener, which will be mentioned in more detail when introducing ApplicationListener below. This object can also be obtained by spring injection.

MessageSourceAware: an extension class used to get MessageSource. MessageSource is mainly used for internationalization.

ApplicationContextAware: an extension class used to get ApplicationContext. ApplicationContext should be a class that many people are familiar with, that is, the spring context manager, which can manually obtain any bean registered in the spring context. We often extend this interface to cache the spring context and wrap it as a static method. At the same time, ApplicationContext also implements interfaces such as BeanFactory,MessageSource,ApplicationEventPublisher, which can also be used to do things related to interfaces.

10.BeanNameAware

Org.springframework.beans.factory.BeanNameAware

As you can see, this class is also a kind of Aware extension. Before the initialization of bean, that is, before postProcessBeforeInitialization, there is only one trigger point method for this class: setBeanName

The usage scenario is: the user can extend this point, get the beanName registered in the spring container before initializing the bean, and modify the value of the beanName from the line.

The expansion method is:

Public class NormalBeanA implements BeanNameAware {public NormalBeanA () {System.out.println ("NormalBean constructor");} @ Override public void setBeanName (String name) {System.out.println ("[BeanNameAware]" + name);}}

11.@PostConstruct

Javax.annotation.PostConstruct

This is not an extension point, it is actually an annotation. Its purpose is that during the initialization phase of bean, if @ PostConstruct is marked on a method, this method will be called first. The point here is to pay attention to the trigger point of this standard, which is after postProcessBeforeInitialization and before InitializingBean.afterPropertiesSet.

Usage scenario: users can annotate a method to initialize a property

The expansion method is:

Public class NormalBeanA {public NormalBeanA () {System.out.println ("NormalBean constructor");} @ PostConstruct public void init () {System.out.println ("[PostConstruct] NormalBeanA");}}

12.InitializingBean

Org.springframework.beans.factory.InitializingBean

This class, as its name implies, is also used to initialize bean. The InitializingBean interface provides a way for bean to initialize the method, which only includes the afterPropertiesSet method, which is executed when the bean is initialized by any class that inherits the interface. This extension point is triggered before postProcessAfterInitialization.

Usage scenario: users implement this API to initialize some business indicators when the system is started.

The expansion method is:

Public class NormalBeanA implements InitializingBean {@ Override public void afterPropertiesSet () throws Exception {System.out.println ("[InitializingBean] NormalBeanA");}}

13.FactoryBean

Org.springframework.beans.factory.FactoryBean

In general, Spring uses the class attribute of bean to specify the feeder class to instantiate bean through the reflection mechanism. In some cases, the process of instantiating Bean is complicated. If you follow the traditional way, you need to provide a lot of configuration information in bean. The flexibility of configuration is limited, so coding may lead to a simple solution. Spring provides a factory class interface for org.springframework.bean.factory.FactoryBean for this purpose, and users can customize the logic of instantiating Bean by implementing this interface. The FactoryBean interface occupies an important position for the Spring framework, and Spring itself provides more than 70 FactoryBean implementations. They hide the details of instantiating some complex bean and bring convenience to the upper application. Starting with Spring3.0, FactoryBean supports generics, that is, interface declarations are changed to the form of FactoryBean

Usage scenario: users can extend this class to act as a proxy for the bean to be instantiated, such as intercepting all the methods of the object and outputting a line of log before and after the call, imitating the function of ProxyFactoryBean. Extension: SpringBoot content aggregation

The expansion method is:

Public class TestFactoryBean implements FactoryBean {@ Override public TestFactoryBean.TestFactoryInnerBean getObject () throws Exception {System.out.println ("[FactoryBean] getObject"); return new TestFactoryBean.TestFactoryInnerBean ();} @ Override public Class getObjectType () {return TestFactoryBean.TestFactoryInnerBean.class;} @ Override public boolean isSingleton () {return true } public static class TestFactoryInnerBean {}}

14.SmartInitializingSingleton

Org.springframework.beans.factory.SmartInitializingSingleton

There is only one method in this interface, afterSingletonsInstantiated, which is a callback interface that is called after all singleton objects (non-lazily loaded objects) managed by the spring container are initialized. The trigger time is after postProcessAfterInitialization.

Usage scenario: users can extend this API to do some post-processing after initializing all singleton objects.

The expansion method is:

Public class TestSmartInitializingSingleton implements SmartInitializingSingleton {@ Override public void afterSingletonsInstantiated () {System.out.println ("[TestSmartInitializingSingleton]");}}

15.CommandLineRunner

Org.springframework.boot.CommandLineRunner

There is only one method for this interface: run (String...) Args), the trigger time is automatically executed after the whole project is started. If you have more than one CommandLineRunner, you can use @ Order to sort.

Usage scenario: users extend this API to preprocess some businesses after starting the project.

The expansion method is:

Public class TestCommandLineRunner implements CommandLineRunner {@ Override public void run (String... Args) throws Exception {System.out.println ("[TestCommandLineRunner]");}}

16.DisposableBean

Org.springframework.beans.factory.DisposableBean

There is also only one method for this extension point: destroy (), which is triggered automatically when the object is destroyed. For example, when you run applicationContext.registerShutdownHook, this method is triggered.

The expansion method is:

Public class NormalBeanA implements DisposableBean {@ Override public void destroy () throws Exception {System.out.println ("[DisposableBean] NormalBeanA");}}

17.ApplicationListener

Org.springframework.context.ApplicationListener

To be exact, this should not be regarded as an extension point in spring&springboot. ApplicationListener can listen on the event of an event, the trigger time can be interspersed with the execution of business methods, and users can customize a business event. But there are also some built-in events within spring that can be interspersed with startup calls. We can also take advantage of this feature to do some built-in event listeners to achieve roughly the same thing as some of the previous triggers.

Next, list the main built-in events of spring:

ContextRefreshedEvent

This event is published when the ApplicationContext is initialized or refreshed. This can also happen using the refresh () method in the ConfigurableApplicationContext interface. Initialization here means that all Bean is loaded successfully, post-processing Bean is detected and activated, all Singleton Bean is pre-instantiated, and the ApplicationContext container is ready for use.

ContextStartedEvent

This event is published when ApplicationContext is started using the start () method in the ConfigurableApplicationContext (ApplicationContext subinterface) interface. You can investigate your database, or you can restart any stopped application after receiving this event.

ContextStoppedEvent

This event is published when ApplicationContext is stopped using stop () in the ConfigurableApplicationContext interface. You can do the necessary clean-up work after receiving this incident.

ContextClosedEvent

This event is published when ApplicationContext is turned off using the close () method in the ConfigurableApplicationContext interface. A closed context reaches the end of the life cycle; it cannot be refreshed or restarted

RequestHandledEvent

This is a web-specific event that tells all bean HTTP requests that they have been served. It can only be applied to Web applications that use DispatcherServlet. When Spring is used as the front-end MVC controller, the event will be triggered automatically when the user request is processed by Spring.

From these spring&springboot extension points, we can roughly peep into the entire bean life cycle. When developing the business or writing the middleware business, we can make good use of the extension points provided to us by spring to do something in the various stages of spring startup. To achieve the purpose of custom initialization.

These are the Springboot startup extension points that Xiaobian shared with you. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report