Spring表达式
对<property>进行统一编程,所有的内容都使用value
<property name="" value="#{表达式}">
#{123}、#{‘jack‘} :数字、字符串
#{beanId}:另一个bean的引用
#{beanId.propName}:操作数据
#{beanId.toString()}:执行方法
#{T(类).字段|方法}:静态方法或字段
1. Address.java
1 package com.gyf.model; 2 3 public class Address { 4 private String name; 5 6 public String getName() { 7 return name; 8 } 9 10 public void setName(String name) { 11 this.name = name; 12 } 13 14 @Override 15 public String toString() { 16 return "Address{" + 17 "name=‘" + name + ‘\‘‘ + 18 ‘}‘; 19 } 20 }
2. Cutomer.java
1 package com.gyf.model; 2 3 public class Customer { 4 private String name; 5 private String sex="男"; 6 private double pi; 7 private Address address; 8 9 public Address getAddress() { 10 return address; 11 } 12 13 public void setAddress(Address address) { 14 this.address = address; 15 } 16 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 public String getSex() { 26 return sex; 27 } 28 29 public void setSex(String sex) { 30 this.sex = sex; 31 } 32 33 public double getPi() { 34 return pi; 35 } 36 37 public void setPi(double pi) { 38 this.pi = pi; 39 } 40 41 @Override 42 public String toString() { 43 return "Customer{" + 44 "name=‘" + name + ‘\‘‘ + 45 ", sex=‘" + sex + ‘\‘‘ + 46 ", pi=" + pi + 47 ‘}‘; 48 } 49 }
3. beans8.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation=" 5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <!--创建一个地址对象--> 8 <bean id="address" class="com.gyf.model.Address"> 9 <property name="name" value="#{‘天河‘}"></property> 10 </bean> 11 12 <bean id="customer" class="com.gyf.model.Customer"> 13 <property name="name" value="#{‘gyf‘.toUpperCase()}"></property> 14 <!--Math.PI调用静态方法--> 15 <property name="pi" value="#{T(java.lang.Math).PI}"></property> 16 <!--ref引用,一个对象引用另外一个对象,这是写法一 17 <property name="address" ref="address"></property> 18 --> 19 <!--ref引用写法二--> 20 <property name="address" value="#{address}"></property> 21 </bean> 22 23 </beans>
4. Lesson08.java
1 package com.gyf.test; 2 3 import com.gyf.model.Customer; 4 5 import org.junit.Test; 6 import org.springframework.context.ApplicationContext; 7 import org.springframework.context.support.ClassPathXmlApplicationContext; 8 9 public class Lesson08 { 10 /** 11 * SpEL Spring 表达式 12 */ 13 @Test 14 public void test1(){ 15 ApplicationContext context = new ClassPathXmlApplicationContext("beans8.xml"); 16 Customer customer = (Customer) context.getBean("customer"); 17 System.out.println(customer.getAddress()); 18 } 19 }
原文:https://www.cnblogs.com/upyang/p/13586231.html