在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配置文件。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。