Spring Instantiates bean process parsing and complete code examples

  • 2020-12-19 20:59:10
  • OfStack

Ask questions

The instantiation of Bean in Spring is an important part of the Bean life cycle, and usually Bean will not change after it is initialized.

So what exactly is the process for Spring instance Bean? !

Spring Instantiates bean process analysis

To get an bean object, first get it through the getBean() method of BeanFactory, during which the bean object will be instantiated through a series of steps:

Step 1: Call the default constructor for Bean (or any other constructor you specify) and generate an instance of bean: bean1.

Step 2: Check whether the Bean configuration file has injected the attribute value of Bean. If so, inject the attribute value of bean1 based on the instance of bean1, overwrite the original bean1 to form a new instance of bean: bean2.

Step 3: Check whether Bean implements the InitializingBean interface, and if it does, override bean2 to form a new instance of bean: bean3 by calling the afterPropertiesSet() method to perform the corresponding operation on bean2.

Step 4: Check whether the attribute es51EN-ES52en is specified in the Bean configuration file. If so, call the corresponding method of this attribute and operate on bean3, and finally overwrite bean3 to form a new instance: bean4.

From the above steps, we find that bean is constantly changing when an instance of Spring is 1 bean!

Spring Instantiates the bean procedural code demonstration

To illustrate the above steps, see the following code:

Entity class:


/** 
 *  Entity class  
 */
public class Employee implements InitializingBean, DisposableBean, BeanNameAware {
	private String id;
	//  Employee number  
	private String name;
	//  Employee name  
	private String sex;
	//  Employees' gender  
	private String age;
	//  Workers age  
	private String nativePlace;
	//  Employees native  
	private String department;
	//  Department employees  
	private String beanName;
	// bean The name of the  
	public Employee() {
		System.out.println("********** The first 1 Step: call Bean The default constructor for **********");
		this.id = "bean1:G080405214";
		System.out.println("bean1 the   Value: " + this);
		System.out.println("********** The first 2 Step: check Bean Is injected in the configuration file Bean The attribute value **********");
	}
	public void afterPropertiesSet() throws Exception {
		System.out.println("bean2 Value: " + this);
		System.out.println("********** The first 3 Step: check Bean Has it been implemented InitializingBean interface **********");
		this.name = "bean3: li ";
		this.sex = "bean3: female ";
		this.age = "bean3:25";
		System.out.println("bean3 Value: " + this);
	}
	public void init() {
		System.out 
		        .println("********** The first 4 Step: check Bean Is specified in the configuration file init-method This property **********");
		this.nativePlace = "bean3: Beijing ";
		System.out.println("bean4 Value: " + this);
	}
	public void destroy() throws Exception {
		System.out.println("********** Service is down **********");
	}
	public void setBeanName(String arg0) {
		System.out.println("********** Set up the bean The name of the **********");
		this.beanName = "myBeanName";
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getNativePlace() {
		return nativePlace;
	}
	public void setNativePlace(String nativePlace) {
		this.nativePlace = nativePlace;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
	public String getBeanName() {
		return beanName;
	}
	@Override 
	  public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", sex=" + sex 
		        + ", age=" + age + ", nativePlace=" + nativePlace 
		        + ", department=" + department + ", beanName=" + beanName + "]";
	}
}

Tools:


/** 
 * Bean Context tool class  
 */
public class BeanContextHelper {
	private static ApplicationContext _instance;
	static {
		if (_instance == null) 
		      _instance = buildApplicationContext();
	}
	private BeanContextHelper() {
	}
	/** 
   *  To rebuild ApplicationContext object  
   */
	public static ApplicationContext buildApplicationContext() {
		return new ClassPathXmlApplicationContext("applicationContext-base.xml");
	}
	/** 
   *  To obtain 1 a ApplicationContext object  
   */
	public static ApplicationContext getApplicationContext() {
		return _instance;
	}
}

Bean configuration:


<?xml version="1.0" encoding="UTF-8"?> 
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
 
  <!--============== test Spring BeanFactory instantiation Bean The process of --> 
  <bean id="employee" class="bean_factory_test.Employee" 
    init-method="init" destroy-method="destroy"> 
    <!-- The default department is the R&D department --> 
    <property name="department"> 
      <value>bean2: Research and development department </value> 
    </property> 
  </bean> 
 
</beans>

The test class:


/** 
 * BeanFactory instantiation Bean Engineering test class  
 */
public class Test {
	public static void main(String args[]) {
		Test test = new Test();
		test.test();
	}
	public void test() {
		ApplicationContext context = BeanContextHelper.getApplicationContext();
		Employee employee = (Employee) context.getBean("employee");
		System.out.println("********** from Spring BeanFactory To get the final bean The instance **********");
		System.out.println(" In the end bean Value: " + employee);
	}
}

Operation results:


********** The first 1 Step: call Bean The default constructor for ********** 
bean1 the   Value: Employee [id=bean1:G080405214, name=null, sex=null, age=null, nativePlace=null, department=null, beanName=null] 
********** The first 2 Step: check Bean Is injected in the configuration file Bean The attribute value ********** 
********** Set up the bean The name of the ********** 
bean2 Value: Employee [id=bean1:G080405214, name=null, sex=null, age=null, nativePlace=null, department=bean2: Research and development department , beanName=myBeanName] 
********** The first 3 Step: check Bean Has it been implemented InitializingBean interface ********** 
bean3 Value: Employee [id=bean1:G080405214, name=bean3: li , sex=bean3: female , age=bean3:25, nativePlace=null, department=bean2: Research and development department , beanName=myBeanName] 
********** The first 4 Step: check Bean Is specified in the configuration file init-method This property ********** 
bean4 Value: Employee [id=bean1:G080405214, name=bean3: li , sex=bean3: female , age=bean3:25, nativePlace=bean3: Beijing , department=bean2: Research and development department , beanName=myBeanName] 
********** from Spring BeanFactory To get the final bean The instance ********** 
 In the end bean Value: Employee [id=bean1:G080405214, name=bean3: li , sex=bean3: female , age=bean3:25, nativePlace=bean3: Beijing , department=bean2: Research and development department , beanName=myBeanName]

From the running results, it should be clear how the Bean instantiation process works.

Employee implements three interfaces:

InitializingBean: This interface provides the afterPropertiesSet() method, which provides the ability to define initialization for bean.
DisposableBean: This interface provides the destroy() method, which provides the ability to operate before the bean instance is destroyed.
BeanNameAware: This interface provides the setBeanName() method, which provides the ability to set the bean name, as you can see from the above run, in step 2.

conclusion

That is the end of this article on Spring's instantiation of bean, and I hope you found it helpful. Those who are interested can continue to see this site:

Two Ways to Get bean by Implementing Aware Interface Custom

Spring Annotation Configuration bean Instance Code Analysis

Bean Life Cycle Details for Spring Configuration Use

If there is any deficiency, please let me know. Thank you for your support!


Related articles: