preface
To introduce the Java constructors, static code block, block structure, @ PostConstruct, InitializingBean interface afterPropertiesSet method of XML configuration of init – method in container starts, the initialization process; @ PreDestroy, DisposableBean interfaces of destroy and destroy – method of XML configuration, container is destroyed, destroy them
So several Spring Bean initialization mode, but the initialization Bean, Bean static code block, block structure, the constructor and other initialization method of execution order, this also is needs us to master, may encounter an interview, one day is similar to the initialization process mentioned in this article
This article is not describing the life cycle of a SpringBean, but we will talk more about it later. What we are describing today is the execution order of a Bean’s internal methods
Initialization mode
SpringBean initialization methods, I believe you are familiar, today we will explain annotation injection and configuration file injection. Let’s take a look at annotation injection and configuration file injection
annotations
Common Spring annotations are: @Component, @repository,@Service,@Controller,(@Configuration, @bean, etc.) but each annotation has a different application scenario, but you can use any one of them to decorate your presentation layer. The service layer and the data layer, but if you decorate your data layer and the service layer with an @Controller, wouldn’t you feel sick seeing that code? Wouldn’t it be better for each to do his or her job? Here’s a brief introduction of each annotation, which will be explained in more detail later in the article
@Repository
Spring2.0 adds, a mechanism that encapsulates storage, retrieval, and search behavior, A collection of mock objects that you can label on any class to indicate that the class is used to perform database-related operations and to support automatic handling of exceptions generated by database operations. It is designed in accordance with DDD: Domain-driven Design(DDD) It’s an object-oriented modeling approach that integrates software system analysis and design, which we’ll talk about later
@Service
The Spring2.5 addition and its twin, @component and @controller, are all produced in Spring2.5. The main markup is in the service layer, which handles the core business logic. If DB is used, @repository injected beans can also be produced in compliance with DDD
@Controller
Spring2.5, as mentioned above, is mainly used as the interpretation and presentation layer. It is used as a web Controller. All the interaction on the front page is with the @controller modified class ErAdvice handles global exceptions, but it was added in Spring 3.2.
@Component
Spring2.5 added, why did @Component come last, because @Component can be applied to any class. Can you go back to @repository, @service, @controller Are decorated with @Component. Any class marked with @Component annotations can be added to the container
The configuration file
The annotation approach is no different from the configuration file approach, except that the annotations don’t need to configure the beans themselves in the XML. Right
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.ijson"/>
<bean class="com.ijson.MyBeanService" init-method="initMethod" destroy-method="destroyMethod"/>
<context:annotation-config/>
<task:annotation-driven/>
</beans>
Copy the code
Initialization process
So with that in mind, let’s talk about the next two initialization methods: their constructors, static code blocks, the initialization process of the construction code blocks, and with the XML above let’s take a look at the code, and the order of execution can be referenced in the comments in the code
package com.ijson;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/** * desc: * author: cuiyongxu * create_time: 2021/8/24-3:55 PM **/
public class MyBeanService implements InitializingBean.DisposableBean {
static {
System.out.println("static");/ / 1
}
static {
System.out.println("static-2");/ / 2
}
{
System.out.println("{} - 1");/ / 3
}
{
System.out.println("{} - 2");/ / 4
}
public MyBeanService(a) {
System.out.println("MyBeanService");/ / 5
}
@PostConstruct
public void init2(a) {
System.out.println("init2");/ / 6
}
@PostConstruct
public void init(a) {
System.out.println("init");/ / 7
}
@Override
public void afterPropertiesSet(a) throws Exception {
System.out.println("afterPropertiesSet");/ / 8
}
public void initMethod(a) {
System.out.println("init-method");/ / 9
}
/** * the bean destruction sequence, when terminating the container, the destruction process */
@PreDestroy
public void preDestroy(a) {
System.out.println("preDestroy");/ / 1
}
@PreDestroy
public void preDestroy2(a) {
System.out.println("preDestroy2");/ / 2
}
@Override
public void destroy(a) throws Exception {
System.out.println("destroy");/ / 3
}
private void destroyMethod(a) {
System.out.println("destroy-method");/ / 4}}Copy the code
The following code is decompiled, why decompiled? Look at the summary
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.ijson;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class MyBeanService implements InitializingBean.DisposableBean {
public MyBeanService(a) {
System.out.println("{} - 1");
System.out.println("{} - 2");
System.out.println("MyBeanService");
}
@PostConstruct
public void init2(a) {
System.out.println("init2");
}
@PostConstruct
public void init(a) {
System.out.println("init");
}
public void afterPropertiesSet(a) throws Exception {
System.out.println("afterPropertiesSet");
}
public void initMethod(a) {
System.out.println("init-method");
}
@PreDestroy
public void preDestroy(a) {
System.out.println("preDestroy");
}
@PreDestroy
public void preDestroy2(a) {
System.out.println("preDestroy2");
}
public void destroy(a) throws Exception {
System.out.println("destroy");
}
private void destroyMethod(a) {
System.out.println("destroy-method");
}
static {
System.out.println("static");
System.out.println("static-2"); }}Copy the code
Conclusion:
Static code blocks: Takes precedence over other code blocks and constructors. They are executed once during class initialization and then destroyed. If there are more than one static code block in a class, they are executed in written order
Construct code block: called when the object is created, it is called once when the object is created. In our example, it is only executed once because the Bean is not destroyed once it is loaded into the container. He carried out prior to the constructor, need to pay attention to, tectonic block of code is not a priority in the constructor, but on the constructor, that is to say, you don’t instantiate objects, tectonic block of code is not executed, look at the compiled MyBeanService constructors, we see the code block code is added to the constructor, and the structure Before you build the function code, you rely on the constructor
Constructor: The constructor must be named exactly as the class name, has no explicit return type, and is called automatically when the current class is initialized
@PostConstruct: First, it’s nota Spring annotation. It’s in rT.jar, derived from Common Annotations 1.0, and was added to the JDK as a new feature when JDK6 was released, after the constructor, if there are multiple @postconstructs in a class It will be executed in the order written
InitializingBean: Includes only the afterPropertiesSet method, which is executed when the bean is initialized by a class that inherits the interface. If the user implements a security policy, the security manager is executed first and then afterPropertiesSet is executed. If not, afterPropertiesSet is executed directly, as shown in the source code in the following figure
Init-method: this is only available when using an XML configuration file and is executed after afterPropertiesSet, as shown in the source code below
Init-method: init-method: if you look at the screenshot above, you should know which method to execute after, so I won’t go into details here
Destruction of the process
See the code above. The last few lines have the logic to destroy, as described in the XML file
@predestroy is understood to be executed before the current Bean is destroyed and is called by the server only once. If multiple @Predestroy annotated methods appear on the same Bean, they are executed in written order
DisposableBean: Destroy Allows a callback to be made before the container destroys the Bean, as shown below
Destroy-method: this method is executed once after destroy
See ibo-java constructs, static code blocks, and SpringBean initialization and destruction processes for more good articles