Open Tao Spring3 (3.3)-di 3.3 more knowledge of Di

Source: Internet
Author: User

3.3.1 Deferred Initialization bean

Lazy initialization, also known as lazy initialization, is to create and initialize a bean only when it is actually used, rather than initializing the bean in advance.

Configuration is simple simply specify the "Lazy-init" property value of "true" on the <bean> tab to defer initialization of the bean.

The spring container initializes the bean for the "singleton" scope when the container is created, and "Singleton" is the singleton meaning that the entire container has only one instance per bean, which is described in detail behind. Spring Container Pre-initialization beans often help us to detect configuration errors in advance , so if nothing is recommended, unless there is a bean that might need to load a lot of resources and is likely to be used throughout the application life cycle, Can be set to deferred initialization.

A bean that is lazily initialized is usually initialized on the first use , or is initialized when the bean is initialized with a non-deferred initialization bean as a dependent object because the deferred initialization bean is used at thistime.

The container management initialization bean eliminates the programmatic implementation of lazy initialization, which is completely controlled by the container, simply configured on a bean definition that requires lazy initialization, simpler than programming, and without intrusive code.

The specific configuration is as follows:

<bean id= "Helloapi"      class= "Cn.javass.spring.chapter2.helloworld.HelloImpl"      lazy- Init= "true"/>  

3.3.2 Using depends-on

Depends-on refers to the order in which the bean is initialized and destroyed, and the bean specified with the depends-on attribute initializes the current bean after initialization , since only the "singleton" Bean can be destroyed by spring management. So when the specified bean is "singleton", the bean specified with the Depends-on property is destroyed after the specified bean.

The configuration is as follows:

    class= "Cn.javass.spring.chapter2.helloworld.HelloImpl"/>      <bean id= "Decorator"          class = "Cn.javass.spring.chapter3.bean.HelloApiDecorator"          depends-on= "Helloapi" >          < Property Name= "Helloapi" ><ref bean= "Helloapi"/></property>      </bean>  

"Decorator" Specifies the "depends-on" property as "Helloapi", so "Helloapi" is initialized before the "decorator" Bean is initialized, and "Helloapi" is destroyed before "decorator" is destroyed , please note that the destruction sequence is inconsistent with the document.

The "depends-on" property can specify multiple beans, and if you specify multiple beans, you can split them with ";", ",", and space.

What good is that "depends-on"? The main is to give a clear initialization and destruction sequence, such as to initialize the "decorator" to ensure that the "HELLOAPI" Bean resources are ready, otherwise the use of "decorator" will not see the prepared resources, and in the destruction of the first in the "decorator" The bean's reference to the "Helloapi" resource is released in order to destroy "Helloapi", otherwise the "Helloapi" may be destroyed and "decorator" also maintain access to resources, causing resources to not release or release errors.

Let's look at an example, in the normal development we may need to access the file system, and the file open, close must be paired, cannot be opened and not closed, resulting in other programs can not access the file. Let's look at the specific configuration:

The specific code is as follows:

1.ResourceBean

 PackageLqy.springh5;ImportJava.io.File; Importjava.io.FileNotFoundException; ImportJava.io.FileOutputStream; Importjava.io.IOException;  Public classResourcebean {PrivateFileOutputStream Fos; Privatefile file; //Initialize Method     Public voidinit () {System.out.println ("resourcebean:======== Initialization"); //load resources, here just to demonstrateSystem.out.println ("resourcebean:======== load resources, perform some pre-operation"); Try {               This. Fos =Newfileoutputstream (file); } Catch(FileNotFoundException e) {e.printstacktrace (); }      }      //method of destroying resources     Public voiddestroy () {System.out.println ("resourcebean:======== Destruction"); //Freeing ResourcesSystem.out.println ("resourcebean:======== frees resources, performs some cleanup operations"); Try{fos.close (); } Catch(IOException e) {e.printstacktrace (); }      }       PublicFileOutputStream Getfos () {returnFos; }       Public voidsetfile (file file) { This. File =file; }  }  

2.DependentBean

 PackageLqy.springh5;Importjava.io.IOException;  Public classDependentbean {Resourcebean resourcebean;  Public voidWrite (String ss)throwsIOException {System.out.println ("dependentbean:======= Write Resources");      Resourcebean.getfos (). Write (Ss.getbytes ()); }      //Initialize Method     Public voidInit ()throwsIOException {System.out.println ("dependentbean:======= Initialization"); Resourcebean.getfos (). Write ("dependentbean:======= Initialize =====". GetBytes ()); }      //Method of Destruction     Public voidDestroy ()throwsIOException {System.out.println ("dependentbean:======= Destruction"); //you need to write the contents to the file before destroying it.Resourcebean.getfos (). Write ("dependentbean:======= destroys =====". GetBytes ()); }            Public voidSetresourcebean (Resourcebean resourcebean) { This. Resourcebean =Resourcebean; }  }  

3.springh5.xml

<?XML version= "1.0" encoding= "UTF-8"?>  <Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/c Ontext/spring-context-3.0.xsd ">      <BeanID= "Resourcebean"class= "Lqy.springh5.ResourceBean"Init-method= "Init"Destroy-method= "Destroy">          < Propertyname= "File"value= "D:/test.txt"/>      </Bean>      <BeanID= "Dependentbean"class= "Lqy.springh5.DependentBean"Init-method= "Init"Destroy-method= "Destroy"depends-on= "Resourcebean">          < Propertyname= "Resourcebean"ref= "Resourcebean"/>      </Bean>  </Beans>

<property name= "file" value= "D:/test.txt"/> Configuration: The spring container can automatically convert a string to Java.io.File.

init-method= "Init" : Specifies the initialization method, which executes after the constructor injection and setter injection are complete.

destroy-method= "Destroy" : Specify the Destruction method, only the "singleton" scope can be destroyed, "prototype" scope must not be, other scopes may not;

In this configuration, Resourcebean initialization is initialized before Dependentbean, and Resourcebean destruction is performed after the Dependentbean is destroyed.

Test it:

 PackageLqy.springh5;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classapp5{ Public Static voidMain (string[] args)throwsException {classpathxmlapplicationcontext context=NewClasspathxmlapplicationcontext ("Springh5.xml"); //a bit to register destroy callback, otherwise we define the destruction method does not executeContext.registershutdownhook (); Dependentbean Dependentbean= Context.getbean ("Dependentbean", Dependentbean.class); Dependentbean.write ("AAA"); }}

The test is exactly the same as the other tests, except that we must register the Destroy method callback, otherwise the destruction method will not execute.

Text of the Test.txt

Note: Context.registershutdownhook (); If the comment is not executed, the Destroy method does not callback the

Open Tao Spring3 (3.3)-di 3.3 more knowledge of Di

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.