Spring配置中的bean引用其它bean的属性值

这项功能在spring的3.0版本以上才支持,如果使用较早的版本(如2.5),会造成转换异常(如将String转换为int)以及不能解析赋值字符串。

需要的jar包:spring的核心包以及Apache的commons-logging包。

public class Polishing {
	int laboratory = 1;

	public int getLavatory(int lavatory) {
		return lavatory;
	}

	// Getters and setters are omitted
}


public class Freight {
	int laboratory;
	int slurry;
	int compensatory;

	// Getters and setters are omitted
}


beans.xml:
<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-3.0.xsd">        
	<bean id="polishing" class="com.john.spring.Polishing" />
	<bean id="freight" class="com.john.spring.Freight">
		<property name="laboratory" value="#{polishing.laboratory}" />
		<property name="slurry" value="#{polishing.getLaboratory()}" />
		<property name="compensatory" value="#{polishing.getLavatory(4)}" />
	</bean>
</beans>


测试类:
public class Perplex {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		Freight bean2 = (Freight) ctx.getBean("freight");
		System.out.println(bean2.getLaboratory());
		System.out.println(bean2.getSlurry());
		System.out.println(bean2.getCompensatory());
	}
}

你可能感兴趣的:(java,spring,bean,xml)