两个简单Bean,后来利用 SpEL 注入值到属性,在 XML 和 注释。
public class Customer {
private Item item;
private String itemName;
}
public class Item {
private String name;
private int qty;
}
<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="itemBean" class="com.yiibai.core.Item">
<property name="name" value="itemA" />
<property name="qty" value="10" />
bean>
<bean id="customerBean" class="com.yiibai.core.Customer">
<property name="item" value="#{itemBean}" />
<property name="itemName" value="#{itemBean.name}" />
bean>
beans>
在注解使用使用SpEL,必须通过注解注册您的组件。如果注册bean在XML和Java类中定义@Value,该@Value将无法执行
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{itemBean}")
private Item item;
@Value("#{itemBean.name}")
private String itemName;
//...
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("itemA") //inject String directly
private String name;
@Value("10") //inject interger directly
private int qty;
public String getName() {
return name;
}
//...
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.yiibai.core" />
beans>
在注解模式下,可以使用@Value定义Spring EL。在这种情况下,一个String和Integer值直接注入到“itemBean”,之后又注入“itemBean”到“customerBean”属性
运行它,无论是使用 SpEL在XML 还是注释都显示了同样的结果:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
}
}
输出结果
Customer [item=Item [name=itemA, qty=10], itemName=itemA]