SpringXML方式配置bean的自動裝配autowire


Spring的自動裝配,也就是定義bean的時候讓spring自動幫你匹配到所需的bean,而不需要我們自己指定了。

例如:

User實體類里面有一個屬性role

1
2
3
4
5
6
7
public class User {
     private int id;
     private String username;
     private String password;
     private Role role;
     /*****省略get and set****/
}

在我們的applicationConext.xml文件里,假如有兩個role對象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<? xml version = "1.0" encoding = "UTF-8" ?>
     xsi:schemaLocation="http://www.springframework.org/schema/beans
 
     < bean id = "role" class = "com.fz.entity.Role" ></ bean >
     < bean id = "role1" class = "com.fz.entity.Role" ></ bean >
     < bean name = "user" class = "com.fz.entity.User" scope = "prototype" >
         < property name = "role" ref = "role" ></ property >
     </ bean >
</ beans >

此時<property name="role" ref="role"></property>找到的就是第一個role對象,但是在bean上配置上了autowire之后,則可以不用寫<property name="role" ref="role"></property>這個屬性了。則是如下的寫法:

1
2
3
4
5
6
7
8
9
10
11
<? xml version = "1.0" encoding = "UTF-8" ?>
     xsi:schemaLocation="http://www.springframework.org/schema/beans
 
     < bean id = "role1" class = "com.fz.entity.Role" ></ bean >
     < bean id = "role2" class = "com.fz.entity.Role" ></ bean >
     < bean name = "user" class = "com.fz.entity.User" scope = "prototype" autowire = "default" >       
     </ bean >
</ beans >


autowire的意思就是spring幫你匹配容器里的bean,而匹配規則有如下幾種


default:如果在bean上指定了default,則它會去beans標簽上去找default-autowire屬性

no:不匹配,但是bean必須定義ref元素

byName:根據名字匹配(如果容器里沒有該name的bean,則該屬性為null)

byType:根據類型匹配(如果同時找多個相同類型的bean,則報錯)

constructor:根據構造器匹配(很少使用)


總結:

1、autowire可以寫在bean上,也可以寫在根元素beans上(寫在beans則表示所有的bean都按此規則來自動匹配)

<bean autowire="byName">     <beans autowire="byName">
















免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM