Spring系列教程——07Spring表达式讲解
下一篇:Spring系列教程——08集合注入讲解
本节我们将讲解Spring的SpEL表达式。
SpEL表达式语法:
对<property>进行统一编程,所有的内容都使用value
<property name="" value="#{表达式}">
#{123}、#{'jack'}:数字、字符串
#{beanId}:另一个bean引用
#{beanId.propName}:操作数据
#{beanId.toString()}:执行方法
#{T(类).字段|方法}:静态方法或字段
下面我们对上述语法一一演示:
首先创建类Address
package domain;
public class Address {
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
private String address;
}
创建类Customer
package domain;
public class Customer {
private String name;
private Address address;
private double money;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
", address=" + address +
", money=" + money +
'}';
}
}
1.数字、字符串
配置如下:
<bean id="customer" class="domain.Customer">
<property name="money" value="#{3.14}"></property>
<property name="name" value="#{'jack'}"></property>
</bean>
测试代码如下:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Customer customer = (Customer) context.getBean("customer");
System.out.println(customer);
2.另一个bean引用
<bean id="address" class="domain.Address">
<property name="address" value="武汉"></property>
</bean>
<bean id="customer" class="domain.Customer">
<property name="money" value="#{3.14}"></property>
<property name="address" ref="address"></property>
<property name="name" value="#{'jack'}"></property>
</bean>
3.操作数据
<bean id="address" class="domain.Address">
<property name="address" value="武汉"></property>
</bean>
<bean id="customer" class="domain.Customer">
<property name="money" value="#{3.14}"></property>
<property name="name" value="#{address.address}"></property>
</bean>
4.执行方法
<bean id="address" class="domain.Address">
<property name="address" value="武汉"></property>
</bean>
<bean id="customer" class="domain.Customer">
<property name="money" value="#{3.14}"></property>
<property name="name" value="#{address.toString()}"></property>
</bean>
5.静态方法或字段
<bean id="address" class="domain.Address">
<property name="address" value="武汉"></property>
</bean>
<bean id="customer" class="domain.Customer">
<!--静态字段-->
<property name="money" value="#{T(Math).PI}"></property>
<property name="address" ref="address"></property>
<property name="name" value="#{'jack'}"></property>
</bean>
静态方法这里不演示了,读者可以自行操作
。
上一篇:Spring系列教程——06参数注入
下一篇:Spring系列教程——08集合注入讲解