一、什么是SpEL表达式
SpEL表达式语言是一种表达式语言,是一种可以与一个基于spring的应用程序中的运行时对象交互的东西,总得来说SpEL表达式是一种简化开发的表达式,通过使用表达式来简化开发,减少一些逻辑、配置的编写。
二、简单的配置代码实现
1、Address和Customer类
public class Address {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Address{" +
"name='" + name + '\'' +
'}';
}
}
public class Customer {
private String name;
private String sex = "男";
private double pi;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public double getPi() {
return pi;
}
public void setPi(double pi) {
this.pi = pi;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", pi=" + pi +
'}';
}
}
2、beans.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--
spel:spring表达式
<property name="" value="#{表达式}">
#{123}、#{'jack’} :数字、字符串 //这样复杂写法的好处是‘’里面的内容是一个对象可以调用方法
#{T(类).字段|方法}:静态方法或字段
# {beanId]:另一个bean引用
# {beanId. propName}:操作数据
# {beanId.toString()}:执行方
-->
<!--创建一个地址bean-->
<bean id="address" class="com.model.Address">
<property name="name" value="中南民族大学"></property>
</bean>
<bean id="customer" class="com.model.Customer">
<property name="name" value="#{'cjx'.toUpperCase()}"></property>
<!--Math.pi 调用静态方法-->
<property name="pi" value="#{T(java.lang.Math).PI}"></property>
<!-- 正常的一个对象引用另一个对象的两种方法
1.ref 关键字
<property name="address" ref="address"></property
2. # {beanId]:另一个bean引用
-->
<property name="address" value="#{address}"></property>
</bean>
</beans>
3、创建Lesson测试
public class Lesson3 {
@Test
public void test() throws Exception{
/*
* spel:spring表达式
* */
ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
Customer customer = (Customer) context.getBean("customer");
System.out.println(customer);
System.out.println(customer.getAddress());
}
}
4、测试运行结果