使用Spring表达式语言(SpEL),我们可以在创建bean时动态地将对象引用或值注入到bean中,而不是在开发时进行静态定义。在此示例中,您将学习如何使用另一个bean的属性来注入bean的属性。
首先创建两个类,Student和Grade类。学生对象将具有存储其成绩名称的属性,该属性将从成绩对象获得。
package org.nhooo.example.spring.el;
public class Student {
    private String name;
    private String grade;
    public Student() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
}package org.nhooo.example.spring.el;
public class Grade {
    private String name;
    private String description;
    public Grade() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}接下来,我们创建spring配置文件。在此配置中,我们有两个bean定义,gradeand和studentbean。我们设置bean的nameanddescription属性grade。
我们还student使用字符串文字设置bean的name属性。但是,使用Spring EL将grade属性值设置为grade的Bean名称属性#{grade.name}。该表达式告诉spring容器查找id为的bean grade,读取其name并将其分配给student的等级。
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
    <bean id="grade">
        <property name="name" value="Beginner"/>
        <property name="description" value="A beginner grade."/>
    </bean>
    <bean id="student">
        <property name="name" value="Alice"/>
        <property name="grade" value="#{grade.name}"/>
    </bean>
</beans>然后创建以下程序以执行spring容器并从中检索学生bean。
package org.nhooo.example.spring.el;
import org.nhooo.example.spring.model.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpELDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-example.xml");
        Student student = (Student) context.getBean("student");
        System.out.println("Name  = " + student.getName());
        System.out.println("Grade = " + student.getGrade());
    }
}该程序将打印以下输出:
Name = Alice Grade = Beginner