The process of Spring managing javabeans

1. Sparing container manages the initialization process of javabeans

Spring's IOC and AOP:

Initialize Spring context container (IOC)

ApplicationContext ac=new ClassXmlPathApplicationContext("spring.xml");

Spring Bean life cycle:

1) Through XML, Java annotation (annotation) and Java Configuration (configuration class)

Load Spring Beans in other ways

2) BeanDefinitionReader: parses the definition of Bean. During the Spring container startup process,

The Bean will be parsed into Spring's internal BeanDefinition structure;

Understood as: Convert the <bean> tag in spring.xml into a BeanDefinition structure

Somewhat similar to XML parsing

3) BeanDefinition: Contains many properties and methods. For example: id, class (class name),

scope, ref (dependent beans), etc. In fact, the definition information of the bean (such as <bean>)

Store it in the corresponding attribute of this BeanDefinition

For example:

<bean id="" class="" scope=""> -----> BeanDefinition(id/class/scope)

4) BeanFactoryPostProcessor: It is an extension interface of Spring container function.

Notice:

1) BeanFactoryPostProcessor after the spring container loads BeanDefinition,

Executed before bean instantiation

2) Process the bean metadata (BeanDefinition), which is BeanDefinition

Attribute filling, modification and other operations

5) BeanFactory: bean factory. It produces various beans we need according to our requirements.

For example:

BeanFactory -> List<BeanDefinition>

BeanDefinition(id/class/scope/init-method)

<bean class="com.zking.spring02.biz.BookBizImpl"/>

foreach(BeanDefinition bean : List<BeanDefinition>){

   //Instantiate the object according to the class attribute reflection mechanism

   //Reflection assignment to set properties

}6) Aware awareness interface: In actual development, it is often necessary to use the functional resources of the Spring container itself

For example: BeanNameAware, ApplicationContextAware, etc.

BeanDefinition implements BeanNameAware, ApplicationContextAware

7) BeanPostProcessor: post-processor. After the Bean object is instantiated and injected,

Add custom logic before and after calling the initialization method. (Similar to AOP's wraparound advice)

Prerequisite: The post-processor will only be executed if it is detected that the Bean object implements BeanPostProcessor.

Before and After methods

BeanPostProcessor

1)Before

2) Call the initializing Bean (InitializingBean and init-method, the initialization of the Bean is completed)

3) After completes the creation of the Bean

8) destroy: destroy

English

Bean: beans

Definition: definition, elaboration

Reader: read

aware:perception

destroy: destroy

Summarize:

1. Configure javabean in xml/annotation/configuation

2.BeanDefinitionReader parses the configured javaBean to get BeanDefiniton, and finally to BeanDefinition, and finally to a collection of List<BeanDefinitionReader>. To put it bluntly, this is a modeling process.

3. Trigger BeanFactoryPostProcessor and execute your own business before javaBean is initialized;

4. The beanFacotry (bean factory) in spring will traverse and initialize all JavaBean objects through the LIst<BeanDefinitionReader> collection.

5. If your javabean needs to mobilize resources in the spring context (resource refers to methods or properties), then you need an Aware awareness interface.

6. If your javabean has been initialized for you and you still need to extend its functions, you need to use BeanPostProcessor to help you complete it.

2.Is the javabean in spring a singleton or multiple instances:

1. The default is single instance but multiple instances can be configured

2. The advantage of a singleton is that it saves internal purity, but the disadvantage is that it has variable pollution.

  Advantages of multiple examples: no variable pollution, disadvantages: very consuming internal purity

 

 For example, there is another family with two children. Both children want a car. At this time, in order to save money, the family only bought (single case mode) one car. The older brother plays with it in the morning and the younger brother plays with it in the afternoon. After buying the car, my brother plays with it in the morning, and then by the time the younger brother plays in the afternoon, the car may have run out of power, or in other words, the appearance of the car may have been damaged (variable pollution).

The advantage is that you save money (save memory)

So if you buy two (multi-instance mode) cars, then there will be no situation like the above (variable pollution), but you will spend more money (consuming a lot of internal purity)

Code demo:

Singleton:

package xzs.beanlife;

import java.util.List;

import xzs.ioc.serverce.UserServerce;
import xzs.ioc.serverce.impl.UserServerceImpl;
import xzs.ioc.serverce.impl.UserServerceImpl2;

public class ParamAction {
	private int age;
	private String name;
	private List<String> hobby;
	private int num = 1;
	// private UserBiz userBiz = new UserBizImpl1();

	public ParamAction() {
		super();
	}

	public ParamAction(int age, String name, List<String> hobby) {
		super();
		this.age = age;
		this.name = name;
		this.hobby = hobby;
	}

	public void execute() {
		// userBiz.upload();
		// userBiz = new UserBizImpl2();
		System.out.println("this.num=" + this.num++);
		System.out.println(this.name);
		System.out.println(this.age);
		System.out.println(this.hobby);
	}
}

 

package xzs.beanlife;

public class InstanceFactory {
	public void init() {
		System.out.println("初始化方法");
	}

	public void destroy() {
		System.out.println("销毁方法");
	}

	public void service() {
		System.out.println("业务方法");
	}
}
<!--    springde1bean的生命周期-->
    <bean id="paramAction" class="xzs.beanlife.ParamAction">
        <constructor-arg name="name" value="三丰"></constructor-arg>
        <constructor-arg name="age" value="21"></constructor-arg>
        <constructor-arg name="hobby">
            <list>
                <value>抽烟</value>
                <value>烫头</value>
                <value>大保健</value>
            </list>
        </constructor-arg>
    </bean>

    <bean id="instanceFactory" class="com.zking.beanLife.InstanceFactory"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>
</beans>
package xzs.beanlife;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/*
 * spring	bean的生命週期
 * spring	bean的單例多例
 */
public class Demo2 {
	// 体现单例与多例的区别
	@Test
	public void test1() {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		ParamAction p1 = (ParamAction) applicationContext.getBean("paramAction");
		ParamAction p2 = (ParamAction) applicationContext.getBean("paramAction");
		// System.out.println(p1==p2);
		p1.execute();
		p2.execute();
		
//		单例时,容器销毁instanceFactory对象也销毁;多例时,容器销毁对象不一定销毁;
		applicationContext.close();
	}

	// 体现单例与多例的初始化的时间点 instanceFactory
	@Test
	public void test2() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
	}

	// BeanFactory会初始化bean对象,但会根据不同的实现子类采取不同的初始化方式
	// 默认情况下bean的初始化,单例模式立马会执行,但是此时XmlBeanFactory作为子类,单例模式下容器创建,bean依赖没有初始化,只有要获取使用bean对象才进行初始化
	@Test
	public void test3() {
		// ClassPathXmlApplicationContext applicationContext = new
		// ClassPathXmlApplicationContext("/spring-context.xml");

		Resource resource = new ClassPathResource("/spring-context.xml");
		BeanFactory beanFactory = new XmlBeanFactory(resource);
//		InstanceFactory i1 = (InstanceFactory) beanFactory.getBean("instanceFactory");
		
	}

}

Then the running result is:

 Then it can be seen that the singleton mode will indeed cause variable pollution. The first time it is used, it is 1, and the second time it is indeed 2.

Then the following is a demonstration of multiple instance mode:

Note: As mentioned above, the singleton mode is the default, so to use the multiplex mode here, you need to specify:

That is to say, add the scope attribute to the paraAction bean tag and set the value to: prototy

 <bean id="paramAction" class="xzs.beanlife.ParamAction" scope="prototype">
        <constructor-arg name="name" value="三丰"></constructor-arg>
        <constructor-arg name="age" value="21"></constructor-arg>
        <constructor-arg name="hobby">
            <list>
                <value>抽烟</value>
                <value>烫头</value>
                <value>大保健</value>
            </list>
        </constructor-arg>
    </bean>

    <bean id="instanceFactory" class="xzs.beanlife.InstanceFactory"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>
public void test1() {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		ParamAction p1 = (ParamAction) applicationContext.getBean("paramAction");
		ParamAction p2 = (ParamAction) applicationContext.getBean("paramAction");
		 System.out.println(p1==p2);
		p1.execute();
		p2.execute();
		
//		单例时,容器销毁instanceFactory对象也销毁;多例时,容器销毁对象不一定销毁;
		applicationContext.close();
	}

In the above piece of code, we compare p1 and p2 to see if their pure addresses are the same.

result:

 It can be seen that false means that when the specified object is used for the second time, an inner pure space is reopened.

The above is a code demonstration of multiple instance mode and singleton mode.

3. Singleton: Javabean is initialized with the spring context: when the container is born, the object is said to be dead, and when the container is dead, the object is dead.

Multiple examples: Javabeans are created when they are used, and are destroyed following the JVM.

Code verification:

Singleton:

 <bean id="instanceFactory" class="xzs.beanlife.InstanceFactory"
          scope="singleton" init-method="init" destroy-method="destroy"></bean>
public void test2() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
	}

result:

The above code can derive the singleton mode, and the object is initialized in the spring context. 

Multiple examples:

<bean id="instanceFactory" class="xzs.beanlife.InstanceFactory"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>

test:

The instanceFactory tag is not called

public void test2() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
	}

result:

Call instanceFactory tag

public void test2() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		Object instanceFactory = applicationContext.getBean("instanceFactory");
	}

 The initialization method appears when the instanceFactory tag is called, but does not appear when it is not called.

Table of contents

1. Sparing container manages the initialization process of javabeans

Spring Bean life cycle:

2.Is the javabean in spring a singleton or multiple instances:

1. The default is single instance but multiple instances can be configured

2. The advantage of a singleton is that it saves internal purity, but the disadvantage is that it has variable pollution.

  Advantages of multiple examples: no variable pollution, disadvantages: very consuming internal purity

3. Singleton: Javabean is initialized with the spring context: when the container is born, the object is said to be dead, and when the container is dead, the object is dead.

Multiple examples: Javabeans are created when they are used, and are destroyed following the JVM.

4. Paragraph 3 above is not absolutely correct.


public void test3() {
		// ClassPathXmlApplicationContext applicationContext = new
		// ClassPathXmlApplicationContext("/spring-context.xml");

		Resource resource = new ClassPathResource("/spring-context.xml");
		BeanFactory beanFactory = new XmlBeanFactory(resource);
//		InstanceFactory i1 = (InstanceFactory) beanFactory.getBean("instanceFactory");
		
	}
By default, bean initialization will be executed immediately in singleton mode. However, at this time, XmlBeanFactory is a subclass and the container is created in singleton mode. The bean dependency is not initialized. It is only initialized to obtain the bean object.

result:

So use him now

public void test3() {
		// ClassPathXmlApplicationContext applicationContext = new
		// ClassPathXmlApplicationContext("/spring-context.xml");

		Resource resource = new ClassPathResource("/spring-context.xml");
		BeanFactory beanFactory = new XmlBeanFactory(resource);
	InstanceFactory i1 = (InstanceFactory) beanFactory.getBean("instanceFactory");
		
	}

result:

 

Guess you like

Origin blog.csdn.net/weixin_72997875/article/details/132374658