- Spring SpEL 教程
- Spring SpEL - 主页
- Spring SpEL - 概述
- Spring SpEL - 环境设置
- Spring SpEL - 创建项目
- 表达评估
- Spring SpEL - 表达式接口
- Spring SpEL - 评估上下文
- Bean 配置
- Spring SpEL - XML 配置
- Spring SpEL - 注解配置
- 语言参考
- Spring SpEL - 文字表达式
- Spring SpEL - 属性
- Spring SpEL - 数组
- Spring SpEL - 列表
- Spring SpEL - 地图
- Spring SpEL - 方法
- 运营商
- Spring SpEL - 关系运算符
- Spring SpEL - 逻辑运算符
- Spring SpEL - 数学运算符
- Spring SpEL - 赋值运算符
- 特殊操作员
- Spring SpEL - 三元运算符
- Spring SpEL - Elvis Operator
- Spring SpEL - 安全导航操作员
- 收藏
- Spring SpEL - 集合选择
- Spring SpEL - 集合投影
- 其他特性
- Spring SpEL - 构造函数
- Spring SpEL - 变量
- Spring SpEL - 函数
- Spring SpEL - 表达式模板
- Spring SpEL - 有用的资源
- Spring SpEL - 快速指南
- Spring SpEL - 有用的资源
- Spring SpEL - 讨论
Spring SpEL - 基于注释的配置
SpEL 表达式可用于基于注释的 bean 配置
句法
以下是在基于注释的配置中使用表达式的示例。
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private int id;
在这里,我们使用 @Value 注释,并且在属性上指定了 SpEL 表达式。类似地,我们也可以在 setter 方法、构造函数和自动装配期间指定 SpEL 表达式。
@Value("#{ systemProperties['user.country'] }")
public void setCountry(String country) {
this.country = country;
}
以下示例显示了各种用例。
例子
让我们更新在Spring SpEL - 创建项目章节中创建的项目。我们正在添加/更新以下文件 -
Employee.java - 员工类。
AppConfig.java - 配置类。
MainApp.java - 要运行和测试的主应用程序。
这是Employee.java文件的内容-
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Employee {
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private int id;
private String name;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@Value("Mahesh")
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
@Value("#{ systemProperties['user.country'] }")
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "[" + id + ", " + name + ", " + country + "]";
}
}
这是AppConfig.java文件的内容-
package com.tutorialspoint;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.tutorialspoint")
public class AppConfig {
}
这是MainApp.java文件的内容-
package com.tutorialspoint;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.refresh();
Employee emp = context.getBean(Employee.class);
System.out.println(emp);
}
}
输出
[84, Mahesh, IN]