Assembly Bean of Spring Series

Source: Internet
Author: User

I. Overview

The container is the core of the spring framework, and the spring container uses IOC to manage all components that comprise the application system. Spring has two different containers: Beanfactory provides the simplest container, provides the most basic dependency injection support, ApplicationContext based on Beanfactory, provides system architecture services such as subordinate files to read text information, Event delivery, and so on.

When you assemble a bean in a spring container called assembly, when you assemble the bean, you are telling the container which beans are needed and how the container uses dependency injection to tie them together.

II. Assembly Bean 2.1 Using XML assembly

Beanfactory employs a factory design pattern, and its implementation class is responsible for creating and distributing various types of beans.

There are several implementations of beanfactory in spring, such as org.springframework.beans.factory.xml.XmlBeanFactory loading beans based on the definitions in the XML file. (It is not recommended now)

Classpathxmlapplicationcontext: A context that loads a context definition file from a classpath

Filesystemxmlapplicationcontext: An application context that loads a context file from a file system

Xmlwebapplicationcontext: A spring-based Web application context that loads a context definition file from a Web application context

 public  class   testmain{ static  void   main (string[] args) {// applicationcontext ctx=new        Classpathxmlapplicationcontext ("Applicationcontext.xml");  Classpathresource res = new  Classpathresource ("Applicationcontext.xml" ); Beanfactory factory  =//        xmlbeanfactory is now not recommended to use                 Demo2 t= (Demo2) Factory.getbean ("Demo2" );    System.out.println (T.getprice ()); }}
2.2 Adding a bean

The Bean factory reads the bean's definition information from the XML file, but there is no instantiation at this time that the Bean,bean is delayed loaded into the bean factory. The Getbean method is then called, and the factory instantiates the bean and begins to set the Bean's properties using dependency injection.

One of the most basic beanfactory configurations consists of one or more bean definitions that it manages, and in one xmlbeanfactory, the root node beans contains one or more elements

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd "><Beans>  <BeanID="..."class="...">    ...  </Bean>  <BeanID="..."class="...">    ...  </Bean>  ...</Beans>

The bean definitions in a xmlbeanfactory include:

    • ClassName: This is usually the real implementation class of the bean, but if a bean is created using a static factory method instead of being created by a normal constructor, then this is the factory class classname
    • Bean Behavior configuration element: It declares how the bean behaves in a container, such as automatic assembly mode, dependency check mode, initialization and destructor methods
    • Parameters of the constructor and properties required for the newly created Bean: such as the size limit of the pool
    • Other beans related to the bean's work: for example, its collaborators

There are two main types of directional control/Dependency Injection:

1. Setter-based Dependency injection : It is implemented by invoking the setter method on your bean after calling the parameterless constructor or the parameterless static method factory method to instantiate your bean. Spring generally advocates the use of dependency injection based on setter methods. Here is the distance from this method:

The implementation class for the build Bean is Demo1.java:

 Public classdemo1{PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicDemo1 () {System.out.println ("Call no parameter constructor"); }}

The configuration in Applicationcontext.xml is:

 <BeanID= "Demo1"class= "com. Demo1 ">        < Propertyname= "Name">            <value>Xujian</value>        </ Property>            < Propertyname= "Age">            <value>23</value>        </ Property>    </Bean>

To write a test class:

 Public class testmain{    publicstaticvoid  main (string[] args)    {        ApplicationContext Factory=new classpathxmlapplicationcontext ("Applicationcontext.xml");        Demo1 t= (DEMO1) factory.getbean ("Demo1");                System.out.println (T.getname ());}    }

The result of the operation is:

  

As can be seen, the setter method first executes the class's parameterless constructor, and then calls the Setxxx method to set the property.

2. constructor-based dependency injection : It is implemented by invoking a constructor with many parameters, each representing a partner or attribute, as an example of this method

With this approach, you need to add a parameter constructor to the bean's implementation class

 Public classdemo2{PrivateString BookName; Private intPrice ;  PublicString Getbookname () {returnBookName; }     Public voidsetbookname (String bookname) { This. BookName =BookName; }     Public intGetPrice () {returnPrice ; }     Public voidSetprice (intPrice ) {         This. Price =Price ; }     PublicDemo2 (String BookName,intPrice ) {System.out.println ("Execute a parametric constructor!" ");  This. BookName =BookName;  This. Price =Price ; }}

The configuration for the corresponding Applicationcontext.xml is:

 <BeanID= "Demo2"class= "com. Demo2 " >        <Constructor-arg>            <value>Java</value>        </Constructor-arg>        <Constructor-arg>            <value>50</value>        </Constructor-arg>    </Bean>

To write a test class:

 Public class testmain{    publicstaticvoid  main (string[] args)    {        ApplicationContext Factory=new classpathxmlapplicationcontext ("Applicationcontext.xml");        Demo2 t= (DEMO2) factory.getbean ("Demo2");            System.out.println (T.getbookname ());}    }

The result of the execution is:

  

2.3 Prototypes vs. Single instances

Spring, by default, is single-instance mode, and always returns the same instance when the container allocates beans.

The test is as follows:

 Public class testmain{    publicstaticvoid  main (string[] args)    {        ApplicationContext Factory=new classpathxmlapplicationcontext ("Applicationcontext.xml");        Demo2 T1= (Demo2) factory.getbean ("Demo2");            Demo2 t2= (Demo2) factory.getbean ("Demo2");         SYSTEM.OUT.PRINTLN (T1= =t2);}    }

The result of the execution is:

  

If we want to always get a different instance every time we request a bean from the context, we need to configure the scope property, where the default value of scope in the original configuration file is Singleton, which is now set to prototype

<BeanID= "Demo2"class= "com. Demo2 "Scope= "Prototype">        <Constructor-arg>            <value>Java</value>        </Constructor-arg>        <Constructor-arg>            <value>50</value>        </Constructor-arg>    </Bean>

Execute the above test procedure again, the result is as follows:

  

2.4 Instantiation and destruction

When a bean is instantiated, it may be necessary to do some initialization work, delete the need to do some cleanup work, in the bean definition to set their own init-method and Destroy-method and in the XML file configuration, These methods are invoked when the instantiation is created or destroyed. Examples are as follows:

Add two functions to the definition of a Demo2 class

 Public void Initialize ()    {        System.out.println ("executed the initialization function! ");    }      Public void Close ()    {        System.out.println ("executed the Destroy function! ");    }

Then configure the XML file

 <BeanID= "Demo2"class= "com. Demo2 "Init-method= "Initialize"Destroy-method= "Close">        <Constructor-arg>            <value>Java</value>        </Constructor-arg>        <Constructor-arg>            <value>50</value>        </Constructor-arg>    </Bean>

Run the test program

 Public class testmain{    publicstaticvoid  main (string[] args)    {        ApplicationContext Factory=new classpathxmlapplicationcontext ("Applicationcontext.xml");        Demo2 T1= (Demo2) factory.getbean ("Demo2");             System.out.println (T1.getbookname ());         T1.close ();    }}

The results are as follows:

  

2.5 Automatic Assembly

We can implement automatic assembly by setting the Autowire property in the bean. There are four types of automatic assembly:

    • ByName: A bean that tries to find the same property name as the one that needs to be automatically assembled in the container

  

    • Bytype: Look for the same bean in the container as the property type that needs to be automatically assembled

  

    • Constructor: Find one or more beans in the container that match the constructor parameters of the bean that needs to be automatically assembled
    • Null: No automatic assembly mode, bean reference must be defined by ref element

  

  

  

Assembly Bean of Spring Series

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.