In the previous article, the scope,scope of the bean in spring is not only the way beans exist in the spring container, such as prototype and Singleton, but also some of the properties that exist in the period, such as session and request. In spring, beans are instantiated from the dependency injection to the initialization, to the last extinction, and to the complete life cycle. Together with scope, it forms the full life cycle of the bean. This article is a simple description of the initialization method (init ()) in The Bean life cycle and the method before extinction (OnDestroy () and later called destructor). This article mainly discusses the prototype and singleton beans, and because the prototype bean is not managed by spring when it returns to the client, the method before its destruction is not executed.
The Bean's life cycle in spring is as simple as the following:
We can include some of our own custom processing in the life cycle function, such as loading related resources, starting threads, etc. during the initialization phase, releasing resources and shutting down threads during the destruction phase. One thing to keep in mind is that the initialization function does not start until all dependencies have been injected.
Life cycle Callbacks
There are several ways in which beans are initialized and extinct:
1. Spring interfaces Initializingbean and Disposablebean. Examples are as follows:
/** * Initializingbean interface from the name it can be seen that this method executes after the Bean's properties have been assigned by spring, but is coupled with the spring interface/ * @Override public void Afterpropertiesset () throws Exception { System.out.println (this+ "I am afterpropertiesset"); } /* * * Disposablebean interface defined * /@Override public Void Destroy () throws Exception { System.out.println (this+ "I am destroy"); }
2. With a metadata configuration, which is configured in the Bean's definition, such asInit-methodand theDestroy-methodProperties, define the relevant methods directly, in addition to the root tag <beans> can configure the default method of Default-init-method and Default-destroy-method configuration, if there is a definition in <bean>, Overrides the DEFAULT definition:
<bean id= "User0" class= "com.test.service.UserServiceIml" init-method= "Testinit" destroy-method= " Testbeforedesstroy "> <property name=" Userdao "ref=" Userdao "></property></bean>/** * @Description: Configuration in XML with metadata configuration * @param * @return void */public void Testinit () { System.out.println (this+ "I am testinit"); } /** * @Description: Configuration in XML with metadata configuration * @param * @return void */public void Testbeforedesstroy () { System.out.println (this+ "I am Testbeforedesstroy"); }
3. Using JSR annotations
/** * @Description: Using JSR annotations * @param * @return void */ @PostConstruct public Void Testpostconstruct () { System.out.println (this+ "I am testpostconstruct"); } /** * @Description: Annotations with JSR * @param * @return void */ @PreDestroy public void Testpredesstroy () { System.out.println (this+ "I am Testpredesstroy"); }
Mixing mechanism
There are three kinds of callback functions implemented in the way they can be used alone, or can be mixed, mixed use when they are in the order of the following:
For initialization functions:
1. Ways to @PostConstruct annotations
2. Initializingbean interface-defined callback Afterpropertiesset ()
3. Custom initialization functions in bean configuration
The same is true for the destructor:
1. Ways to @PreDestroy annotations
2. Disposablebean interface-defined callback Destroy ()
3. Custom destructor in Bean configuration
Detailed testing is shown in the back.
Startup and shutdown callbacks
Sometimes we may need the functionality of some components to start up with a spring container (such as a new thread for listening), the container is destroyed and destroyed. This spring provides an interface from which the method name can easily be seen:
Public interface Lifecycle { void start (); void Stop (); Boolean isrunning (); }
When started, the order of initiation is quite important due to dependencies between components. The Depends-on property can determine the order in which multiple lifecycle are implemented, but sometimes dependencies are unknown. To do this, spring defines a new interface, Smartlifecycle:
Public interface Phased { int getphase ()} public interface Smartlifecycle extends Lifecycle, phased {boolean-is Autostartup (); void Stop (Runnable callback); }
The Isautostartup decision is that as the container starts and starts, the method defined by the phased interface determines the boot order, the smaller the return value, the earlier the start, and the later the higher the start. If a lifecycle does not implement the phased interface, the default value is 0.
The Stop method can execute the destructor asynchronously, and spring waits 30 seconds for each phase by default. This time can be configured.
Test
In a non-web environment, in order for destructors to execute, the Abstractapplicationcontext Registershutdownhook () method needs to be executed, as shown in the example of this article:
This test preparation illustrates the following:
1. Sequence of execution of mixed-life-cycle callbacks
2. Lifecycle can also be seen as a cycle where the Start method is called after the initialization function is executed, and the Stop method is called before the destructor executes. Prototype will not be called by the start and stop methods
3. Depend-on determines the order in which beans are loaded
4. The callback defined by <bean> overrides the default callback defined by <beans>.
Code
The following is a test program, this program relies on the spring container and configuration of the first knowledge of the code in this article, and slightly changed it:
The code structure is as follows:
The first is the Allbean.xml configuration file:
<!--make JSR annotations effective - <bean id= "postsss" class= " Org.springframework.context.annotation.CommonAnnotationBeanPostProcessor "/> <!--can also use this configuration to make a JSR effective <context:annotation-config/>- <!--change in the container shutdown phase, smartlifecycle each phase waits-- < Bean id= "lifecycleprocessor" class= "Org.springframework.context.support.DefaultLifecycleProcessor" > <! --Timeout value in milliseconds-- <property name= "Timeoutpershutdownphase" value= "+"/> </ bean> <import resource= "Com/test/dao/dao.xml"/> <import resource= "com/test/service/ Service.xml "/>
And then the Service.xml.
<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.O Rg/schema/beans/spring-beans.xsd "default-init-method=" Init "default-destroy-method=" Close "> <!--configure its own initialization and destruction, overriding the default configuration--<bean id= "User0" class= "com.test.service.UserServiceIml" init-method= "Testinit" destroy-method= "Testbeforedesstroy" > <property name= "Userdao" ref= "Userdao" ></property> </bean > <!--initialization and destruction with default configuration--<bean id= "user1" class= "com.test.service.UserServiceIml" > <prope Rty name= "Userdao" ref= "Userdao" ></property> </bean> <!--configuration scope is prototype, test executes only initialization function, do not perform destructor --<bean id= "user2" class= "com.test.service.UserServiceIml" scope= "prototype" > <property name= "use Rdao "ref=" Userdao "></property> </Bean> <!--The following test depend-on--<bean id= "T1" class= "Com.test.service.Test1" depends-on= "T2" > < /bean> <bean id= "T2" class= "Com.test.service.Test2" > </bean> </beans>
The USERSERVICEIML then implements the associated interface, using the JSR annotations and implementing the initialization and destructor configured in the Bean:
Package com.test.service; Import java.util.List; Import Javax.annotation.postconstruct;import Javax.annotation.PreDestroy; Import Org.springframework.beans.factory.disposablebean;import Org.springframework.beans.factory.initializingbean;import org.springframework.context.SmartLifecycle; Import Com.test.bo.user;import Com.test.dao.UserDao; /** * Implementation class, there is a field reference to the Userdao interface, its specific business logic call {@link userdao#getuser ()} implementation * * And there is a set method, this set method is injected by the spring container, if there is no return error, * This is a method of spring container dependency Injection--setter injected */public class Userserviceiml implements Userservice,initializingbean,disposablebean, smartlifecycle{private Volatile Boolean isrunning = false; Private Userdao Userdao; @Override public list<user> GetUser () {return userdao.getuser (); } public void Setuserdao (Userdao userdao) {This.userdao = Userdao; System.out.println (this+ "I am Setmethod"); }/** * Initializingbean interface from the name it can be seen that this method executes after the bean attribute is assigned by spring, but is coupled with the spring interface */@Override public void AfterproPertiesset () throws Exception {System.out.println (this+ "I am Afterpropertiesset"); }/* * * Disposablebean Interface Definition */@Override public void Destroy () throws Exception {System.out.printl N (this+ "I am Destroy"); }/** * @Description: Using JSR annotations * @param * @return void */@PostConstruct public void testpostcons Truct () {System.out.println (this+ "I am testpostconstruct"); }/** * @Description: Annotated with JSR * @param * @return void */@PreDestroy public void Testpredesstroy () { System.out.println (this+ "I am Testpredesstroy"); }/** * @Description: With metadata configuration, configure * @param * @return void */public void Testinit () {SYSTEM.O in XML Ut.println (this+ "I am Testinit"); }/** * @Description: With metadata configuration, configure * @param * @return void */public void Testbeforedesstroy () {in XML) { System.out.println (this+ "I am Testbeforedesstroy"); } public void Init () {System.out.println (this+ "I am init"); } public void Close () {System.out.println (this+ "I am Close"); } @Override public Boolean isrunning () {returnisrunning; } @Override public void Start () {System.out.println (this+ "Spring container Started"); IsRunning = true; }/** * */@Override public void Stop () {System.out.println (this+ "Spring container closed"); IsRunning = false; } @Override public int getphase () {return 0; } @Override public Boolean isautostartup () {return true; } @Override public void Stop (Runnable arg0) {arg0.run (); IsRunning = false; System.out.println (this+ "This is Stop"); }}
Main program:
public class Testmain {public static void Main (string[] args) { abstractapplicationcontext context = new Cla Sspathxmlapplicationcontext ("Allbean.xml"); Context.registershutdownhook (); UserService UserService0 = Context.getbean ("User0", userservice.class); System.out.println (Userservice0.getuser ()); System.out.println ("--------------user1 with default initialization function--------------");// UserService UserService1 = Context.getbean ("user1", userservice.class);// System.out.println (Userservice1.getuser ());// UserService UserService2 = Context.getbean ("User2", userservice.class);// System.out.println ( Userservice2.getuser ()); } }
Test results
The above test results are not analyzed. The first line of the above test results should be noted because the relationship is vacant.
Conclusion
The Bean's life cycle, spring, is managed and extended using beanpostprocessor (called the spring Extension point), and spring defines a number of built-in Beanpostprocessor, Some of their callbacks are invoked during the instantiation of the Bean, which is referred to as a return to the client before the call, not the new, and if the bean implements some aware interfaces such as Applicationcontextaware and Beannameawre
), callbacks for these interfaces also go into the life cycle, which is not discussed for the time being. See article: Http://developer.51cto.com/art/201104/255961.htm. Also, Spring uses proxy mechanisms extensively, and it is important to note that the life cycle functions run before the agent is created. The test code download for this article: full download of this code
The life cycle of spring beans