spring中ref標簽的用法
1、作用
將對象值注入到對應的屬性,依賴於配置標簽實現
2、屬性
- bean:通過該屬性可以引用同一容器或父容器中的bean對象
- parent: 引用父容器中的bean
3、用法
bean屬性用法比較簡單,這里就不再介紹,主要講一下parent屬性的用法
前提
- 一個Boss類中有name,Car屬性,對應一個BossBean.xml配置文件
- 一個Car類中有brand、price、color屬性,對應一個CarBean.xml配置文件
需求
- 在BossBean.xml配置文件中引用CarBean.xml配置文件的bean
Boos類
package com.yl.bean;
public class Boss {
private String name;
private Car car;
public Boss() {
}
public Boss(String name, Car car) {
this.name = name;
this.car = car;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
Car類
package com.yl.bean;
public class Car {
private String brand;
private Integer price;
private String color;
public Car() {
}
public Car(String brand, Integer price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
BossBean.xml配置文件(父容器)
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<!--Boss-->
<bean id="boss" class="com.yl.bean.Boss">
<property name="name" value="yl001"></property>
<property name="car">
<!--引用父容器中的car-->
<ref parent="car"></ref>
</property>
</bean>
</beans>
CarBean.xml配置文件(子容器)
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<!--Car-->
<bean id="car" class="com.yl.bean.Car">
<property name="brand" value="蘭博基尼"></property>
<property name="color" value="紅色"></property>
<property name="price" value="1000000"></property>
</bean>
</beans>
4、測試類
public static void main(String[] args) {
//父容器 (CarBean)
ApplicationContext parentCtx=new ClassPathXmlApplicationContext("CarBean.xml");
//子容器(BoosBean)關聯父容器
ApplicationContext childCtx=new ClassPathXmlApplicationContext(new String[] {"BossBean.xml"},parentCtx);
Boss boss= (Boss) childCtx.getBean("boss");
System.out.println("老板名 ="+boss.getName());
System.out.println("所用的車 ="+boss.getCar().getBrand());
}