Spring配置中的bean直接引用其它bean的屬性值


pring配置中的bean直接引用其它bean的屬性值來賦值給當前bean的屬性,也可以直接調用其它bean的方法獲取返回值來賦值給當前bean的屬性,並且可以進行參數傳遞,這樣可以省去在bean中注入需要獲取屬性值的bean。

以下是一個完整的示例:

1、需要JAVA類:

 

Spring配置中的bean直接引用其它bean的屬性值

package com.service.test;
public class Bean1 {
	int v1 = 1;
	public int getV1() {
		return v1;
	}
	public void setV1(int v1) {
		this.v1 = v1;
	}
	public int getTestValue(int v1) {
		return v1;
	}
	public String getTestValue2(String str) {
		return str;
	}	
}

package com.service.test;
public class Bean2 {
	int v1;
	int v2;
	int v3;
	String v4Str;
	public int getV1() {
		return v1;
	}
	public void setV1(int v1) {
		this.v1 = v1;
	}
	public int getV2() {
		return v2;
	}
	public void setV2(int v2) {
		this.v2 = v2;
	}	
	public int getV3() {
		return v3;
	}
	public void setV3(int v3) {
		this.v3 = v3;
	}
	public String getV4Str() {
		return v4Str;
	}
	public void setV4Str(String str) {
		v4Str = str;
	}	
}
package com.service.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
	/** * @param args */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context = new ClassPathXmlApplicationContext("testBean.xml");
		Bean2 bean2 = (Bean2)context.getBean("bean2");
		System.out.println(bean2.getV1());
		System.out.println(bean2.getV2());
		System.out.println(bean2.getV3());
		System.out.println(bean2.getV4Str());
	}
}

2、需要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-3.1.xsd">
			
	<bean id="bean1" class="com.service.test.Bean1">
	</bean>
	<bean id="bean2" class="com.service.test.Bean2">
		<property name="v1" value="#{bean1.v1}"/>
		<property name="v2" value="#{bean1.getV1()}"/>
		<property name="v3" value="#{bean1.getTestValue(3)}"/>
		<property name="v4Str" value="#{'Hello '+bean1.getTestValue2('baby')}"/>
	</bean>
</beans>


 

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!https://blog.csdn.net/jiangjunshow


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM