The relationship between the beans of the "Spring" IOC container

Source: Internet
Author: User
Tags xml parser

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

In this paper, we mainly talk about the relationship between beans in spring, which are divided into three types: inheritance, dependency and reference. Examples and usage analysis are given in the article.

first, inherit bean configuration
    • Spring allows inheritance of the bean's configuration , the inherited Bean is called the parent bean, and the bean that inherits the parent bean is called the Child bean .
    • The child Bean inherits the configuration from the parent bean, including the Bean's property configuration
    • the child bean can also overwrite the configuration inherited from the parent bean .
    • The parent bean can be configured as a template or as a bean instance, and if you just want to use the parent bean as a template, you can configure the abstract property of <bean> to True so that spring will not instantiate the bean
    • Not all attributes in the <bean> element will be inherited . such as: Autowire,abstract and so on.
    • You can also omit the class property of the parent Bean , let the child bean specify its own class, and share the same property configuration, but this time the abstract must be set to True

Use case:

Define House.java:

Package Com.mucfc;public class House {private string Housesize;private string Houseposition;private string Houseprice; Public String gethousesize () {return housesize;} public void Sethousesize (String housesize) {this.housesize = housesize;} Public String gethouseposition () {return houseposition;} public void Sethouseposition (String houseposition) {this.houseposition = houseposition;} Public String Gethouseprice () {return houseprice;} public void Sethouseprice (String houseprice) {this.houseprice = Houseprice;} Public String toString () {return "House size:" +housesize+ "House Location:" +houseposition+ "house price:" +houseprice;}

If more than one bean has the same configuration information, Spring allows us to define a parent, and the child will automatically inherit the parent's configuration information.

     <!--definition abstract bean--     <bean id= "Abstracthouse" class= "Com.mucfc.House" p:housesize= "150 ping"        p: houseposition= "Keyuan Garden" p:houseprice= "150,000"/>     <!--inherited from Abstracthouse,      <bean id= "House2" parent= " Abstracthouse "p:houseposition="/>      <!--inherited from Abstracthouse, <bean id= "      house3" parent= " Abstracthouse "p:houseprice=" 80,000 "/>
Use:
House House5=applicationcontext.getbean ("House2", House.class); House House6=applicationcontext.getbean ("House3", House.class); System.out.println (HOUSE5); System.out.println (HOUSE6);
Output Result:

House size: 150 Ping House location: Hui King Court house Price: 150,000
House size: 150 Ping House location: Science Garden house price: 80,000


House1 and House2 inherit from the abstractHouse, and spring passes the configuration information of the parent bean to the child bean, if the child bean provides the configuration information that the parent bean already has. Then the child bean will overwrite the parent bean.

The function of the parent bean is primarily to simplify the configuration of the child bean, so it is generally declared as abstract= "true", which means that this is not instantiated as a corresponding bean, if the user does not specify that the property is true, Then the IOC container instantiates a bean named Abstractcar.


second, dependent bean configuration
    • Spring allows the user to set the bean's predecessor-dependent bean through the Depends-on property , which is created before the bean is instantiated by the predecessor-dependent bean .
    • if the predecessor relies on more than one bean, you can configure the bean's name by commas, spaces, or by the way
Depends-on:

The Depends-on property can be used to explicitly force the initialization of one or more beans before the current bean is initialized. The following example uses the Depends-on property to specify the dependency of a bean.

    <bean id= "Buyhouser" class= "Com.mucfc.depend.BuyHouser"/>     

If you need to express a dependency on multiple beans, you can separate the specified bean names in ' depends-on ' with separators, such as commas, spaces, and semicolons. The following

The example uses ' depends-on ' to express dependence on multiple beans.
Deferred initialization of beans;

In the XML configuration file, deferred initialization is controlled by the Lazy-init attribute in the <bean/> element. For example:

    <bean id= "Buyhouser" class= "Com.mucfc.depend.BuyHouser" lazy-init= "true"/>     
When the ApplicationContext implementation loads the above configuration, the Bean-buyhouser set to lazy will not be instantiated in advance of ApplicationContext startup. Not.lazy--sellhouser will be instantiated in advance.

It should be explained that if a bean is set to defer initialization and another singleton bean that is not lazily initialized depends on it, then when ApplicationContext instantiates the singleton bean in advance, It must also ensure that all of the above singleton dependent beans are also pre-initialized, including, of course, the bean that is set to defer instantiation. Therefore, you should not be surprised if the IOC container creates instances of beans that are set to defer instantiation when it is started, because those deferred initialization beans may be injected into a non-deferred initialization singleton Bean somewhere in the configuration.


Examples of Use:
1. Buy a house person Buyhouser.java
Package Com.mucfc.depend;public class Buyhouser {private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public void Initbuyhouser () {System.out.println ("initialized Buyhouser");}}
2, selling the house people Sellhouser.java
Package Com.mucfc.depend;public class Sellhouser {private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public void Initsellhouser () {System.out.println ("initialized Sellhouser");}}
3, housing intermediary Houseagent.java
Package Com.mucfc.depend;public class Houseagent {private Buyhouser buyhouser;private sellhouser sellhouser;public Buyhouser Getbuyhouser () {return buyhouser;} public void Setbuyhouser (Buyhouser buyhouser) {this.buyhouser = Buyhouser;} Public Sellhouser Getsellhouser () {return sellhouser;} public void Setsellhouser (Sellhouser sellhouser) {this.sellhouser = Sellhouser;} public void Inithouseagent () {System.out.println ("initialized Houseagent");}}
4, Beans.xml
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" 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/context/spring-context-3.0.xsd "> <bean id=" houseagent "cl ass= "Com.mucfc.depend.HouseAgent" init-method= "inithouseagent" depends-on= "Buyhouser,sellhouser"/> <bean id= "Buyhouser" class= "Com.mucfc.depend.BuyHouser" init-method= "Initbuyhouser" lazy-init= "true"/> <bean id= " Sellhouser "class=" Com.mucfc.depend.SellHouser "init-method=" Initsellhouser "lazy-init=" true "/> </beans>
5. Testing

Package Com.mucfc.depend;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Test {public static void main (String [] args) {ApplicationContext ctx=new classpathxmlapplicationcontext ("Beans.xml");}}
Results:


Note that here I willBuyhouser and Sellhouser are set to lazy-init= "true", but because the house intermediary houseagent relies on them two, so when you load this beans.xml file, you will still first Buyhouser and Sellhouser instantiation.

Third, reference bean configuration Code structure:
can be written
<bean id= "HouseAgent1" class= "com.mucfc.depend.HouseAgent" p:buyhouser= "Buyhouser" p:sellhouser= "Sellhouser"/ >   <bean id= "HouseAgent2" class= "com.mucfc.depend.HouseAgent" p:buyhouser-ref= "Buyhouser" P: sellhouser-ref= "Sellhouser"/>
or written
  <bean id = "HOUSEAGENT3" class = "com.mucfc.depend.HouseAgent" >        <property name= "Buyhouser" >            < Ref bean= "Buyhouser"/>        </property>        <property name= "Sellhouser" >            <ref local= " Sellhouser "/>        </property>    
<ref local= "xx"/>
Use the "local" property to specify that the target is a pointer to the same file. The value of the index "local" property for this "local" value must be the same as the ID property of the target bean. If there are no matching elements within the same file, the XML parser will prompt an error. Similarly, if the target is within the same XML file, using the "local" variable is the best choice (in order to know the error as early as possible)
<ref bean= "xx"/>
Specifying the target bean as the "bean" attribute is the most general form, which allows the creation of beans indexed to any bean within the same container (whether or not in the same XML file) or in a parent container. The value of the Bean property can be the same as the ID property of the target bean, or it can be the same as a value within the Name property of the target bean

1. Using the local property to specify that the target bean can take advantage of the XML Parser's ability to validate the XML ID reference in the same XML configuration file, without matching elements, the XML parser generates an error, so if the referenced bean is in the same XML configuration file, Then using local form is the best option.
2, so to speak, <ref bean> is to look for all the XML configuration file in the bean; <ref local> is looking for beans in this XML file.
3, <ref> provides the following properties:
1) Bean: Look for the introduced bean in the current Spring XML configuration file, or in other JavaBean in the same beanfactory (ApplicationContext).
2) Local: Look for the introduced bean only in the current Spring XML configuration file.
If the Spring IDE is used, the JavaBean that it relies on can be validated at compile time. Based on the local approach, developers can use the benefits provided by the XML itself for validation. 3) Parent: Specifies the parent JavaBean definition for which it depends.


Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka



The relationship between the beans of the "Spring" IOC container

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.