•为了简化 XML 文件的配置,越来越多的 XML 文件采用属性而非子元素配置信息。
•Spring 从 2.5 版本开始引入了一个新的 p 命名空间,可以通过 <bean> 元素属性的方式配置 Bean 的属性。
•使用 p 命名空间后,基于 XML 的配置方式将进一步简化
•使用ref可以连接其他bean。
例如:
1、普通方法
application.xml
<bean id="helloWorld24" class="com.hello.HelloWorld2" p:id="10" p:name="20" p:pass="30"/>
JavaBean.class
package com.hello;
public class HelloWorld2 {
private int id;
private String name;
private String pass;
public HelloWorld2() {
super();
}
public HelloWorld2(int id, String name, String pass) {
this.id = id;
this.name = name;
this.pass = pass;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public String toString() {
return "HelloWorld2{" +
"id=" + id +
", name='" + name + '\'' +
", pass='" + pass + '\'' +
'}';
}
}
Main.class
package test;
import com.hello.AList;
import com.hello.HelloWorld;
import com.hello.HelloWorld2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest1 {
public static void main(String[] args) {
//创建Spring IOC容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-application.xml");
HelloWorld2 helloWorld2 = (HelloWorld2) applicationContext.getBean("helloWorld24");
System.out.println(helloWorld2);
}
}
2、使用ref连接其他bean
application.xml
<bean id="address" class="com.hello.Address" p:city="淄博" p:road="柳泉路"/>
<bean id="userInfo" class="com.hello.UserInfo" p:id="100" p:name="Hern" p:pass="123456" p:address-ref="address"/>
JavaBean.class
package com.hello;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class Address {
private String city;
private String road;
public Address() {
super();
}
public Address(String city, String road) {
this.city = city;
this.road = road;
}
}
package com.hello;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class UserInfo {
private int id;
private String name;
private String pass;
private Address address;
public UserInfo() {
super();
}
public UserInfo(int id, String name, String pass, Address address) {
this.id = id;
this.name = name;
this.pass = pass;
this.address = address;
}
}
Main.class
package test;
import com.hello.UserInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest2 {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-application2.xml");
UserInfo userInfo = (UserInfo) applicationContext.getBean("userInfo");
System.out.println(userInfo);
}
}