Spring's Set bean value

Source: Internet
Author: User
Tags xml parser

The property values for a Java instance can have many data types, primitive type values, string types, Java instances, and even other bean instances, Java collections, arrays, and so on. So spring allows you to specify values for the properties of the bean instance through the following elements:

Value

Ref

Bean

list, set, map, props

First, Value: Set normal property values

The <value.../> element is used to specify the property values of the string type, base type. Spring uses an XML parser to parse out the data and then uses Java.beans.PropertyEdior to complete the type conversion: from the java.lang.String type to the desired parameter value type. If the target type is a basic data type, it is usually possible to convert correctly.

1 public class Valuetest {2     //define a string property 3     private string name; 4     //define an int Type property 5     private int age; 6
   7 public     String GetName () {8         return name, 9     }10 public     void SetName (String name) {one         this.name = NA me;12     }13     public     int getage () {         return age;16}17 public     void Setage (int. age) {18< C16/>this.age = age;19     }20}

The above example simply demonstrates injecting normal property values. Use the <value.../> element in the spring configuration file to specify attribute values for these two properties.

1 <bean id= "text" class= "com.spring.service.impl.ValueTest" >2         <property name= "Age" value= "1"/>3         <property name= "name" value= "Chenssy"/>4     </bean>

By the above you can know that the <value.../> element is primarily used to pass in string, base type property values.

Second, ref: Configure collaborators

<value.../> mainly configures the property values of the base type, but if we need to set the property value for the bean to be another bean instance, this time we need to use <ref ... The/> element. Use <ref ... The/> element can specify the following two properties.

Bean: Reference the id attribute value of another bean instance that is not in the same XML configuration file.

Local: Reference the id attribute value of another bean instance in the same XML configuration file.

1 <bean id= "Steelaxe" class= "Com.spring.service.impl.SteelAce" ></bean>2     <bean id= "Chinese" class = "Com.spring.service.impl.Chinese" >3         <property name= "Axe" >4 <ref local=             "Steelaxe"/>5         </property>6     </bean>

In fact, Spring provides a more concise notation:

1 <bean id= "Steelaxe" class= "Com.spring.service.impl.SteelAce" ></bean>2     <bean id= "Chinese" class = "Com.spring.service.impl.Chinese" >3         <property name= "Axe" ref= "Steelaxe"/>4     </bean>

By adding the ref attribute to the property, you can set the reference of another bean to the Axe property value. So write the effect and use <ref ... The/> property is the same, and it is not necessary to distinguish between using the bean attribute or the local property, so this is recommended.

2.1. Using automatic assembly to inject the partner bean

Spring supports the automatic assembly of dependencies between beans and beans, which means that we do not need to display the specified dependent beans. The contents of the XML configuration file are examined by Beanfactory, and a dependency is injected into the keynote bean according to a rule.

Spring's automatic assembly mechanism can be specified by the Default-autowire attribute of the <bean.../> element, or by the Autowire attribute of the <bean.../> element.

Automatic assembly reduces the amount of configuration files, but it reduces the transparency and clarity of dependencies, so it is generally deprecated in larger deployment environments, showing that configuration collaborators can get clearer dependencies. Spring provides the following rules for automatic assembly.

No: not suitable for automatic assembly. Bean dependencies must be defined by a REF element.

ByName: Automatically assembled according to the attribute name. Beanfactory Find all the beans in the container and find the bean with the same name as the id attribute to complete the injection. If no matching bean instance is found, spring does not inject any.

Bytype: Automatic assembly by attribute type. Beanfactory finds all the beans in the container, and if there is exactly one bean with the same type of dependency property, it is automatically injected, but if there are multiple such beans, an exception is thrown. If there is no matching bean, nothing will happen and the property will not be set. Set dependency-check= "Objects" if you need to throw an exception if you cannot assemble automatically.

Constructor: Similar to no type, the difference is the parameter used to construct the injection.

Autodetect:beanfactory, depending on the internal structure of the bean, decides to use constructor or Bytype. If a default constructor is found, a byte is used.

ByName Rules

The Bytyep rule refers to injecting a dependency by name, and if the implementation class of Bean A contains the Setb () method, and spring's configuration file contains exactly one bean with ID B, the spring container injects the B instance into Bean a. If the container doesn't have a name match, Bean,spring doesn't do anything.

1 <bean id= "Chinese" class= "Com.spring.service.impl.Chinese" autowire= "byname"/>2     <bean id= "Gundog" class= "Com.spring.service.impl.Gundog" >3         <property name= "name" value= "Wangwang"/>4     </bean >

The above configuration file specifies the byname rule. The following dependency injection method is provided in the Com.app.service.impl.Chinese class:

1/*2      * Dependency must be setter method, because need to automatically assemble by name 3      * So setter method must provide Set+bean name, the first letter of the bean name Capital 4      * @param dog Set the dog value of 5      * /6 Public     void Setgundog (dog dog) {7         This.dog = Dog;8     }

Bytype rules

Bytype rules are injection dependencies based on type matching. If the A instance has a SETB (b-B) method, and the spring configuration file has exactly one bean instance of type B, the container is a bean instance with a injection-type match. If there is more than one instance of B in the container, an exception is thrown and nothing happens if there is no B instance.

1 <bean id= "Chinese" class= "Com.spring.service.impl.Chinese" autowire= "Bytype"/>2     <bean id= "Gundog" class= "Com.spring.service.impl.Gundog" >3         <property name= "name" value= "Wangwang"/>4     </bean >

The Chinese class for the above configuration file has the following methods.

1/**2      * Dependency must be setter Method 3      * Because using automatic assembly by type, the setter method has the same parameter type as the type of the container Bean 4      * Gundog in the program implements the dog interface 5      * @param Dog incoming Dog Object 6      */7 public     void Setdog (dog dog) {8         This.dog = dog;9     }

When a bean uses an automatic assembly dependency and uses ref to display dependencies, the display of the specified dependency overrides the automatic assembly.

By default, spring automatically searches all the beans in the container and judges them to see if they meet the conditions of automatic assembly, and if satisfied, injects the bean into the target bean instance. If we don't want spring to search all the beans in the container, that is, we need spring to determine which beans need to be searched, and which beans do not need to be searched, then we need to use the Autowire-candidate property. By setting autowire-candidate= "false" for the <bean.../> element, you can limit the bean to the automatic assembly range, and the container will not consider the bean when it looks for an auto-assemble object.

Third, Bean: inject nested bean

If a bean relies on a bean that does not want to be accessed directly by the spring container, a nested bean can be used. The <bean.../> element is used to define nested beans, which are only valid for external beans that nest it, and the spring container cannot directly access nested beans, so you do not need to specify an id attribute when defining a nested bean.

1 <bean id= "Chinese" class= "Com.spring.service.impl.Chinese" autowire= "byname" >2         <property name= "Axe" >3             <!--4                 property value is a nested bean, the nested bean cannot be accessed directly by the spring container, 5                 so the nested bean is not required id attribute 6              -->7             <bean class= "Com.spring.service.impl.SteelAce"/>8         </property>9     </bean>

Using the configuration above ensures that nested beans cannot be accessed by the container, so there is no need to worry about other programs modifying nested beans. However, nested beans restrict the access of the bean and improve the cohesion of the program.

Iv. list, set, map, props

The <value.../> element is injected with the basic data type and string type, but what if the property of a bean is a collection? At this point we need to use the collection elements,<list.../>, <set.../>, <map.../>, and <props.../> elements to set the type list, set, The collection property value for map and properties.

Let's look at the following Java classes:

 1 public class Chinese implements person{2 3///The following is a collection of set properties 4 private list<string> schools; 5 private MAP scores; 6 private map<string, axe> phaseaxes; 7 Private Properties Health; 8 Private Set axe;      9 Private string[] books;10 one public list<string> getschools () {return schools;13}14 15 public void Setschools (list<string> schools) {this.schools = schools;17}18-Public Map ge Tscores () {scores;21}22-public void Setscores (Map scores) {this.scores = Scores;2 5}26 public map<string, string> getphaseaxes () {return phaseaxes;29}30 to public voi D setphaseaxes (map<string, string> phaseaxes) {this.phaseaxes = phaseaxes;33}34 public Proper Ties Gethealth () {sethealth return health;37}38 (public void) (Properties health) {This.hea    Lth = health;41}42 43 Public Set Getaxe () {axe;45 return}46-public void Setaxe (Set axe) {this.axe = axe;49 }50 (Public string[] Getbooks () {}54 return books;53 setbooks (string[) {5 6 this.books = books;57}58 public void Useaxe () {60 61}62 63}

The Java code above has an array, list, set, map, Properties. The following is for the configuration file above.

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 3 XM Lns= "Http://www.springframework.org/schema/beans" 4 xsi:schemalocation= "http://www.springframework.org/schema/     Beans 5 Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> 6 <!--define a normal axe Bean and 7 <bean id= "Steelaxe" class= "Com.spring.service.impl.SteelAxe"/> 8 <bean id= "Stoneaxe" class= "com.spring.se Rvice.impl.StoneAxe "/> 9 <!--definition Chinese Bean-->11 <bean id=" Chinese "class=" Com.spring.service . Impl. Chinese ">12 <property name=" Schools ">13 <list>14 <value> Primary School </va Lue>15 <value> Middle School </value>16 <value> University </value>17 <                 /list>18 </property>19 <property name= "scores" >21 <map>22 <entry key="Chinese" value= "/>23 <entry key=" mathematics "value="/>24 <entry key= "foreign language" value= "88             "/>25 </map>26 </property>27 <property name=" Phaseaxes ">29 <map>30 <entry key= "Primitive Society" value-ref= "Stoneaxe"/>31 <entry key= "agriculture Industry Society "value-ref=" Steelaxe "/>32 </map>33 </property>34" <property N Ame= "Health" >36 <props>37 <prop key= "blood pressure" > normal </prop>38 < Prop key= "height" >175</prop>39 </props>40 </property>41 Ty name= "Axe" >43 <set>44 <value> normal string </value>45 <bean class= "Com.spring.service.impl.SteelAxe" ></bean>46 <ref local= "Stoneaxe"/>47 &L t;/set>48 </property>49 <property name= "Books" >51 <list>52 &LT;VALUE&G T;java programming thought </value>53 <value> thinking Rich </value>54 <value> generalship </value&gt ; </list>56 </property>57 </bean>58 </beans>

As you can see from the configuration file above, spring has the same handling of list properties and array properties.

When we use the <list.../>, <set.../>, <map.../> and other elements to configure the collection properties, we also need to manually configure the collection elements. Because the collection element can also be a primitive type value, referencing other beans in the container, nested beans, and collection properties. So these elements can then accept the following sub-elements:

Value: Specifies whether the collection element is a base data type or a character type value.

Ref: Specifies another bean instance in the collection element master container.

Bean: Specifies that the collection element is a nested bean.

list, set, map, props: Specifies that the collection element value is also a collection.

Spring's Set bean value

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.