Spring configuration details (configuration bean scope, configuration lazy loading, spring bean life cycle)

Configure the scope of the bean:

  • By default, the vast majority are singletons, and adding scope = "prototype" to the bean configuration can change the singleton state into a multi-case state.

Test after configuring the bean

<bean id="mybean" class="cn.itshow.MyBean">//单例,测试结果为true
<bean id="mybean" class="cn.itshow.MyBean" scope="prototype">//测试结果为false,说明为多例
@Autowired
private MyBean mybean1;
@Autowired
private MyBean mybean2;
@Test
public void testBean(){
	System.out.println(mybean1 == mybean2);//true  -- false
}

Configure lazy loading

BeanFactory defaults to lazy loading (it is created when it is acquired).
By default , ApplicationContext is urgently loaded (objects are created when the container is created). A
single bean needs to be lazy loaded, and lazy-init = "true" is directly added to the bean.

<bean  id="other" class="cn.it.show.OtherBean" lazy-init="true"></bean>

All beans need to be lazy loaded by adding default = lazy-init = "true" after the spring declaration constraint

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd d" default-lazy-init="true">

The life cycle of beans in Spring

Bean life cycle in Spring: a process from creation to destruction of objects managed in Spring.

  1. Instantiation and initialization:

    The essence is that the Spring container helps us call the parameterless construction (creating objects) and the specified initialization method (generally doing initialization work).
    If the Spring container is a BeanFactory, call [lazy loading] when the object is used.
    If the Spring container is ApplicationContext, the default Call [Urgent Loading] when creating a container.
    Note: Singleton is urgent loading.
    Multiple cases are not, the objects of multiple cases are still lazy loaded (because it does not know how many objects are created, only know how many objects you need when acquiring)

  2. Destruction:
    In essence, the Spring container calls the specified destruction method, but only this method is called, and the object is not destroyed. You can do some destruction and cleanup in the destruction method [release resources, close the stream, close the connection].
    This destruction method is generally called when the container is closed, but after the container is used up in Springtest, the container will be automatically closed, and the destruction method will be automatically called
    . Under normal circumstances, initialization and destruction do not matter, and the framework will automatically manage it.

Published 23 original articles · Like1 · Visits163

Guess you like

Origin blog.csdn.net/weixin_45528650/article/details/105560796