在Spring中,有三種方式注入值到 bean 屬性。
正常的方式
快捷方式
“p” 模式
新建一個User類,它包含username和password兩個屬性,現在使用spring的IOC注入值到該bean。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.example.pojo; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this .username= username; } public String getPassword() { return type; } public void setPassword(String password) { this .password= password; } } |
1.正常方式
在一個“value”標簽注入值,并附有“property”標簽結束。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
< beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> < bean id = "user" class = "com.example.User" > < property name = "username" > < value >scott</ value > </ property > < property name = "password" > < value >tiger</ value > </ property > </ bean > </ beans > |
2.快捷方式
注入值“value”屬性。
1
2
3
4
5
6
7
8
9
10
|
< beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> < bean id = "user" class = "com.example.User" > < property name = "username" value = "scott" /> < property name = "password" value = "tiger" /> </ bean > </ beans > |
3. “p” 模式
通過使用“p”模式作為注入值到一個屬性。
1
2
3
4
5
6
7
8
9
10
|
< 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> < bean id = "user" class = "com.example.User" p:username = "scott" p:password = "tiger" /> </ beans > |
記住聲明 xmlns:p=”http://www.springframework.org/schema/p" 在Spring XML bean配置文件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。