Spring 专题
专题目录
您的位置:java > Spring专题 > Spring EL bean引用实例
Spring EL bean引用实例
作者:--    发布时间:2019-11-20
在spring el,可以使用点(.)符号嵌套属性参考一个bean。例如,“bean.property_name”。
public class customer {
	
	@value("#{addressbean.country}")
	private string country;
在上面的代码片段,它从“addressbean” bean注入了“country”属性到现在的“customer”类的“country”属性的值。

spring el以注解的形式

请参阅下面的例子,演示如何使用使用 spel 引用一个bean,bean属性也它的方法。
package com.h3.core;

import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;

@component("customerbean")
public class customer {

	@value("#{addressbean}")
	private address address;

	@value("#{addressbean.country}")
	private string country;
	
	@value("#{addressbean.getfulladdress('h3')}")
	private string fulladdress;

	//getter and setter methods
	
	@override
	public string tostring() {
		return "customer [address=" + address + "\n, country=" + country
				+ "\n, fulladdress=" + fulladdress + "]";
	}

}
package com.h3.core;

import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;

@component("addressbean")
public class address {

	@value("gaodeng, qiongshang")
	private string street;

	@value("571100")
	private int postcode;

	@value("cn")
	private string country;

	public string getfulladdress(string prefix) {

		return prefix + " : " + street + " " + postcode + " " + country;
	}

	//getter and setter methods

	public void setcountry(string country) {
		this.country = country;
	}

	@override
	public string tostring() {
		return "address [street=" + street + ", postcode=" + postcode
				+ ", country=" + country + "]";
	}

}

执行结果

customer obj = (customer) context.getbean("customerbean");
system.out.println(obj);

输出结果

customer [address=address [street=gaodeng, qiongshang, postcode=571100, country=cn]
, country=cn
, fulladdress=h3 : gaodeng, qiongshang 571100 cn]


spring el以xml的形式

请参阅在xml文件定义bean的等效版本。
<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="customerbean" class="com.h3.core.customer">
		<property name="address" value="#{addressbean}" />
		<property name="country" value="#{addressbean.country}" />
		<property name="fulladdress" value="#{addressbean.getfulladdress('h3')}" />
	</bean>

	<bean id="addressbean" class="com.h3.core.address">
		<property name="street" value="gaodeng, qiongshang" />
		<property name="postcode" value="571100" />
		<property name="country" value="cn" />
	</bean>

</beans>

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册