如果属性类型是另外一个被装载的类,可以使用标签来装配属性值。
比如一个JavaBean中的某个属性是另外一个JavaBean的对象,而且要装备这个属性,那么就需要使用来标签ref进行装配。
MyBean类的hello属性是HelloService的类型,代码如下:
MyBean.java
package chapter22;
public class MyBean {
private int iValue;
private String strName;
private HelloService hello;
public int getiValue() {
return iValue;
}
public void setiValue(int iValue) {
this.iValue = iValue;
}
public String getStrName() {
System.out.println("getStrName()方法被调用");
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
System.out.println("setStrName()方法被调用");
}
public HelloService getHello() {
System.out.println("getHello()方法被调用");
return hello;
}
public void setHello(HelloService hello) {
this.hello = hello;
System.out.println("setHello()方法被调用");
}
}
然后在applicationContext.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" 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="helloservice" class="chapter22.HelloServiceImpl">
<property name="greeting" value="greeting Xu Wei">
</property>
</bean>
<bean id="myBean" class="chapter22.MyBean">
<property name="hello">
<ref bean="helloservice" />
</property>
<property name="strName" value="Xu Wei"></property>
</bean>
</beans>
TestMyBean.java
package chapter22;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestMyBean {
public static void main(String args[]) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"src//applicationContext.xml");
MyBean mb = (MyBean) ctx.getBean("myBean");
// System.out.println(mb.getHello());
System.out.println(mb.getHello().getGreeting());
System.out.println(mb.getStrName());
}
}
log4j:WARN No appenders could be found for logger (org.springframework.context.support.FileSystemXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
setGreeting()方法被调用
setHello()方法被调用
setStrName()方法被调用
getHello()方法被调用
getGreeting()方法被调用
greeting Xu Wei
getStrName()方法被调用
Xu Wei
分析:
mb.getStrName是直接传参进去的,而这里通过ref穿进去的是hello,hello本身是一个对象,所以mb.getHello().getGreeting()获得的是hello配置的参数。