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

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

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

Java代码 复制代码  收藏代码
  1. public class Polishing {   
  2.     int laboratory = 1;   
  3.   
  4.     public int getLavatory(int lavatory) {   
  5.         return lavatory;   
  6.     }   
  7.   
  8.     // Getters and setters are omitted   
  9. }  
public class Polishing {
	int laboratory = 1;

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

	// Getters and setters are omitted
}


Java代码 复制代码  收藏代码
  1. public class Freight {   
  2.     int laboratory;   
  3.     int slurry;   
  4.     int compensatory;   
  5.   
  6.     // Getters and setters are omitted   
  7. }  
public class Freight {
	int laboratory;
	int slurry;
	int compensatory;

	// Getters and setters are omitted
}


beans.xml:
Xml代码 复制代码  收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="     
  4.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">           
  5.     <bean id="polishing" class="com.john.spring.Polishing" />  
  6.     <bean id="freight" class="com.john.spring.Freight">  
  7.         <property name="laboratory" value="#{polishing.laboratory}" />  
  8.         <property name="slurry" value="#{polishing.getLaboratory()}" />  
  9.         <property name="compensatory" value="#{polishing.getLavatory(4)}" />  
  10.     </bean>  
  11. </beans>  


测试类:
Java代码 复制代码  收藏代码
  1. public class Perplex {   
  2.     public static void main(String[] args) {   
  3.         ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");   
  4.         Freight bean2 = (Freight) ctx.getBean("freight");   
  5.         System.out.println(bean2.getLaboratory());   
  6.         System.out.println(bean2.getSlurry());   
  7.         System.out.println(bean2.getCompensatory());   
  8.     }   
  9. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值