13. Spring Bean Scope and Lifecycle

Bean scope and life cycle


·         Bean scope

 Spring3 defines 5 scopes for beans , namely singleton (singleton), prototype (prototype), request, session and global session. The 5 scopes are described as follows:

1.    singleton : Singleton mode, there is only one shared bean instance in the Spring IoC container, no matter how many beans reference it, it always points to the same object. The Singleton scope is the default scope in Spring. You can also explicitly define a Bean as a singleton mode, and configure it as:

·        <bean id="userDao"class="com.ioc.UserDaoImpl" scope="singleton"/>

2.    prototype: Prototype mode, every time the bean defined by the prototype is obtained through the Spring container, the container will create a new Bean instance, each bean instance has its own properties and state, and the singleton has only one global object.

As a rule of thumb, use prototype scope for stateful beans and singleton scope for stateless beans .

3.    request : In an Http request, the container will return the same instance of the bean. For different Http requests, a new bean will be generated, and the bean is only valid within the current Http Request.

·         <beanid="loginAction" class="com.cnblogs.Login"scope="request"/>, for each Http request, the Spring container creates a new instance according to the definition of the bean, and the instance is only used in the current Http request It is valid within the request, and other requests cannot see the changes in the state of the current request. When the current Http request ends, the bean instance will also be destroyed.

4.    Session : In an Http Session , the container will return the same instance of the Bean. For different Session requests, a new instance will be created, and the bean instance is only valid within the current Session.

·         <beanid="userPreference" class="com.ioc.UserPreference"scope="session"/>, the same as Http request, each session request creates a new instance, and different instances do not share attributes, and the instance It is only valid within its own session request. When the request ends, the instance will be destroyed.

5.    global Session : In a global Http Session , the container will return the same instance of the bean, which is only valid when using portlet context.

 

 

·         Bean life cycle

After the introduction of the bean scope as above, the life cycle of the bean will be explained on the basis of the bean scope.

  The Spring container can manage the life cycle of beans in the singleton scope. In this scope, Spring can know exactly when a bean is created, initialized, and destroyed. For beans with prototype scope, Spring is only responsible for creating them. When the container creates an instance of the bean, the instance of the bean is handed over to the client's code management. The Spring container will no longer track its life cycle and will not manage those The life cycle of beans configured as prototype scope. The execution of the Bean life cycle in Spring is a very complicated process, and readers can use the methods provided by Spring to customize the Bean creation process. The Spring container does a lot of work before making sure a bean instance is available:

1. Spring instantiates the Bean (equivalent to new Xx() in the program)

2. Spring injects the value and the reference of the bean into the property corresponding to the bean, that is, IOC injection

3. If the Bean implements the BeanNameAware interface, Spring passes the Bean's ID to the setBeanName() method
(the main purpose of implementing BeanNameAware is to obtain the Bean 's ID through the Bean's reference, and the Bean's ID is rarely used in general business )

4. If the Bean implements the BeanFactoryAware interface, Spring will call the setBeanDactory(BeanFactory) method and pass in the BeanFactory container instance as a parameter.
(The main purpose of implementing BeanFactoryAware is to obtain the Spring container (in order to obtain the container, so as to call things in the container) , such as Beans publishing events through
the Spring container, etc.) The Spring factory itself (you can use this method to obtain other beans )

5. (You can use this method to get other beans , used in the project, and return the class ) If the bean implements the ApplicationContextAwaer interface, the Spring container will call the setApplicationContext(ApplicationContext) method, (similar to the BeanFactory, it is to obtain the Spring container, For example, Bean publishes events through the Spring container, etc., the project is to call the bean in the container as Handler. applicationContext .getBeansOfType(EventHandler.class ) ;

Get all classbeans for event processing for further consumer event processing 2), the difference is that the Spring container will pass itself as a parameter of setApplicationContext when calling the setApplicationContext method , and the Spring container needs to be specified by the programmer before calling setBeanDactory (Injection) The parameter BeanFactory in setBeanDactory) is passed into the Spring context. This method can also implement step 4 , but it is better than 4 , because ApplicationContext is a sub-interface of BeanFactory and has more implementation methods . ( If the Spring factory is also applied If it is BeanFactory , it is OK to remove this step .

 

 

6. If the Bean implements the BeanPostProcess interface, Spring will call their postProcessBeforeInitialization (pre-initialization) method
(the function is to perform enhancement processing after the Bean instance is successfully created, such as modifying the Bean and adding a certain function)

7. If the Bean implements the InitializingBean interface , Spring will call their afterPropertiesSet method, which is the same as using the init-method declaration for the Bean in the configuration file. The initialization method is executed after all the properties of the Bean are successfully set .

8. If the Bean implements the BeanPostProcess interface, Spring will call their postProcessAfterInitialization (post-initialization) method
(the same as 6, except that 6 is executed before the Bean is initialized, and this is executed after the Bean is initialized, and the timing is different. )

9. After the above work, the bean is ready and will stay in the application context for the application to use until the application context is destroyed.

 

When the bean is no longer needed, it goes through the cleanup phase.

10. If the Bean implements the DispostbleBean interface, Spring will call its destroy method,

11. If you use the destroy-method attribute on the bean in the configuration file , the effect is the same as that in 10, and they are all methods executed before the bean instance is destroyed.

1. Instantiate the Bean

For the BeanFactory container, when the client requests an uninitialized bean from the container, or when the bean needs to be injected with another uninitialized dependency, the container will call createBean to instantiate it.
For the ApplicationContext container, all beans are instantiated when the container is started.
The container is instantiated by obtaining the information in the BeanDefinition object. And this step is just a simple instantiation without dependency injection.
The instantiated object is wrapped in a BeanWrapper object, BeanWrapper provides an interface for setting object properties, thus avoiding the use of reflection mechanism to set properties.

2. Set object properties (dependency injection)

The instantiated object is encapsulated in the BeanWrapper object, and the object is still in a native state at this time, and no dependency injection is performed.
Next, Spring performs dependency injection based on the information in the BeanDefinition.
And the dependency injection is completed through the interface for setting properties provided by BeanWrapper.

3. Inject the Aware interface

Next, Spring will detect whether the object implements the xxxAware interface and inject the relevant xxxAware instance into the bean. (automatic assembly process)

4. BeanPostProcessor

After the above steps, the bean object has been correctly constructed, but if you want to do some custom processing before the object is used, you can implement it through the BeanPostProcessor interface .
This interface provides two functions:

  • postProcessBeforeInitialzation( Object bean, String beanName )
    The bean object currently being initialized will be passed in, and we can do anything with this bean.
    This function will be executed before InitialzationBean , so it is called preprocessing.
    The injection of all Aware interfaces is done in this step.
  • postProcessAfterInitialzation( Object bean, String beanName )
    The bean object currently being initialized will be passed in, and we can do anything with this bean.
    This function will be executed after the InitialzationBean completes, so it is called post-processing.

5. InitializingBean与init-method

When the preprocessing of BeanPostProcessor is completed, it will enter this stage.
The InitializingBean interface has only one function:

  • afterPropertiesSet()//This is used in the project. Then when registering the bean, execute at the same time

At this stage, we can also add our custom logic before the formal construction of the bean is completed, but it is different from the preprocessing. Since this function does not pass in the current bean object, there is no way to process the object itself in this step, only Can add some extra logic.
To use it, we need to make the bean implement this interface and write the logic to be added in this function. Then Spring will detect whether the current bean implements the interface after the preprocessing is completed, and execute the afterPropertiesSet function.

Of course, in order to reduce the intrusiveness to the client code, Spring provides the init-method attribute for the bean configuration, which specifies the function name that needs to be executed at this stage. Spring will execute the function we set during the initialization phase. The init-method essentially still uses the InitializingBean interface (the initializing method performed).

6. DisposableBean和destroy-method

Like init-method, by assigning a function to destroy-method, the specified logic can be executed before the bean is destroyed.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651669&siteId=291194637