1. The background

Caution: There will be a lot of code inconsistencies in this article.

When looking at the source code of some frameworks, you can see that many of them are combined with Spring. Take an example of the dubbo configuration:

If you also need to build a framework that works with Spring, or if you want to know how other Spring frameworks work with Spring, you should learn about Spring’s extension mechanism.

2. How to scale

In this article, I want to show you how to extend from two Spring processes: container initialization and Bean creation.

2.1 Container initialization

To use Spring, the first step is definitely to initialize the container. Have a refresh in AbstractApplicationContext method defines the container how to refresh:

The detailed flow in REFRESH is shown below:

2.1.1 load BeanDefinition

Before loading a BeanDefinition, let’s take a look at what a BeanDefinition is. As the name implies, a BeanDefinition describes information about a Bean, such as its class information, attribute information, whether it is a singleton, whether it is lazy loaded, etc.

How do I load it? There are generally two approaches, one through our XML and one through some extension.

The XML is loaded as follows:

We configure the definition of such a bean in Spring’s XML, which parses and transforms it into our BeanDefinition.

Another way is through XML Schema extensions. For a more detailed introduction to XSD, see this article: XML Schema Extension mechanisms in Spring. Some students will ask isn’t there a way to annotate? When we were studying, we used to write both XML and annotations in books, and annotations actually use the extension mechanism of XML Schema, which I’ll talk about in a minute.

2.1.1.1 XML Schema Extension

What are extensions to XML Schema?

Spring allows you to define your own XML structure and parse it with your own bean parser. Here are four steps to customize an extension by referring to the XML Schema extension mechanism in Spring:

  • Write an XML schema file describing your node elements.

    Define the demo. XSD file in the resources/ meta-INF/directory. Here we define a node element of demo with a name field defined.

  • Write an implementation class for NamespaceHandler

  • Write one or more implementations of BeanDefinitionParser (key steps).

  • Register the above schema and handler. Create a spring.handler file under the resources/ meta-INF/directory and enter:
http\://www.demo.com/schema/demo = xsd.DemoNameSpaceHandler
Copy the code

This step maps the URL of our previous tag to our NamespaceHandler. Create a new spring.Schemas file and type:

http\://www.demo.me/schema/demo/demo.xsd= META-INF/demo.xsd
Copy the code

This step maps the URL of the XSD.

Going back to annotations, people typically configure annotations using the following figure:

Also using this extension mechanism are AOP,MVC,Spring-Cache and some of our open source frameworks such as Dubbo.

2.1.1.2 spring BeanFactoryPostProcessor extension

This mechanism allows us to modify the BeanDefinition before actually instantiating the Bean.

Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid

Then we create a druid.properties input:

url=jdbc:mysql://localhost:3306/test
username=root
password=123456
Copy the code

Play has been content to this kind of configuration, but there is a problem in the company, the password in plain code stored in project, it is no good, others as long as received your project view permissions password will be compromised, so there will be a unified general company password storage service, only sufficient permissions to be able to use, So we can put the password in the unified storage service and use the password through a call to the service, so how do we inject the password from the remote service into our Bean? Then use our BeanFactoryPostpRrocessor, the following code inheritance is accomplished (BeanFactoryPostpRrocessor implementation class) :

In XML there are:

In this way we can have several benefits:

  • Set up the unified configuration center, so we don’t need to modify the files in our project, just need to modify the configuration center page.
  • Set up a unified password center, so we don’t have to expose the plaintext in the project, how the password is protected and just throw it at the password center.

2.2 Bean creation

Generally, we get a Bean from the API as follows:

You can see the actual creation of the bean in CreateBean. For the actual creation of the bean, there is the following flow:

2.2.1 Aware interface

Spring provides a number of Aware interfaces for extensions, and with Aware we can set as many things as we want:

InvokeAwareMethod provides three kinds of most basic Aware, if is ApplicationContext so round in ApplicationContextAwareProcessor and Aware injection.

  • BeanNameAware: If Spring detects that the current object implements the interface, it sets the beanName of the object instance to the peer object instance.
  • BeanClassLoaderAware: the ClassLoader that loaded the current Bean will be injected into it.
  • BeanFactoryAware: Injects the current BeanFactory container.

ApplicaitonContext container ApplicaitonContext container ApplicaitonContext container

  • EnvironmentAware: Inject context Enviroment into EnvironmentAware, which can be used to obtain configuration properties.

  • EmbeddedValueResolverAware: context EmbeddedValueResolver injected, commonly used in argument parsing. ResourceLoaderAware: Set the context.

  • ApplicationEventPublisherAware: in the ApplicationContext ApplicationEventPublisher interface is achieved, so can be injected.

  • MessageSourceAware: Inject itself.

  • ApplicationContextAware: This is the one we see a lot, injecting its own container into it.

2.2.2 BeanPostProcessor

In the spring BeanFactoryPostProcessor we said before, the two names like, is used for the spring BeanFactoryPostProcessor the BeanFactory BeanDefinition in processing, when the Bean is not generated. The BeanPostProcessor is used to process our generated beans.

Has a special BeanPostProcessor, InstantiationAwareBeanPostProcessor, it will be before we instantiate the process, if implements this interface, it can use its return to the object instance, will not enter the subsequent processes.

A: What’s the use of the BeanPostProcessor?

If you have a need to run each method in a project, you can easily think of using AOP. If you don’t use AOP then you can use BeanPostProcessor’s post-processing method to dynamically proxy each Bean.

2.2.3 InitializingBean/init – method

Spring provides an extension to our Bean initialization logic:

  • Implement the InitalizingBean interface:

    In the afterPropertiesSet() method we can write our initialization logic.

  • Using XML:

2.2.4 DisposableBean/destory – method

As the saying goes, life and death go round and round. So we have live extensions, and naturally Spring provides dead extensions. We can also implement our destruction logic with the following two extensions:

  • DisposableBean: Implement the DisposableBean interface

  • To realize XML:

    Define the destroy method in destroy-method.

PS: if you want to in our Spring container automatically when the JVM close so we can call the close method (ClassPathXmlApplicationContext applicationContext). RegisterShutdownHook (); Register the closing hook so that our Bean can be safely destroyed when the JVM is shut down.

3. Summary

This article has led to a number of basic extension points from the Spring container startup principles and Bean initialization principles. Of course, these extension points are only part of Spring, so you can read the Spring documentation or read the Spring source code. If you can master these extensions, you will need to combine them with Spring when you build your own wheels.

This article is included in JGrowing, a comprehensive, excellent, community-co-built Java learning path. If you want to participate in the maintenance of open source projects, you can co-build it. The address is github.com/javagrowing… A little star, please.

Finally, if you think this article has an article for you, you can pay attention to my technical public number, recently the author collected a lot of the latest learning materials video and interview materials, you can get after attention, your attention and forwarding is the biggest support for me, O(∩_∩)O