SpringEL表达式
SpEL 是一种强大、简洁的装配 Bean 的方式,它可以通过运行期间执行的表达式将值装配到属性或构造函数当中,更可以调用 JDK 中提供的静态常量,获取外部 Properties 文件中的的配置。
环境说明
- JDK 17
- Spring 6.0.6
注入外部属性
创建 test.properties 文件:
name=xiaoMing
在配置类上添加@PropertySource注解,引入test.properties配置文件:
@Configuration
@ComponentScan("com.example.bean")
@PropertySource("classpath:test.properties")
public class MainConfig {
通过@Value注解将配置文件中的属性值注入到Bean中:
@Component
public class Student {
@Value("${name}") //格式:"${key}"
private String name;
也可以将属性值注入到方法参数中:
public Student(@Value("${name}") String name, Teacher teacher) {
this.name = name;
this.teacher = teacher;
}
直接注入常量值:
public Student(@Value("10") String name) {
this.name = name;
}
SpEL简单使用
创建一个SpEL表达式:
public static void main(String[] args){
SpelExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World!!!'");
System.out.println(exp.getValue());
SpEL具有运算能力,因此还可以在创建SpEL表达式时对字符串进行操作:
public static void main(String[] args){
SpelExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World!!!'.bytes");
System.out.println(exp.getValue());
集合操作相关语法
创建并操作List集合:
SpelExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("{5, 2, 1, 4, 6, 7, 0, 3, 9, 8}");
System.out.println(exp.getValue());
创建并操作Map集合:
SpelExpressionParser parser = new SpelExpressionParser();
Expression exp2 = parser.parseExpression("{name: '小明', info: {address: '北京市朝阳区', tel: 10086}}");
Map<String, Object> map = (Map<String, Object>) exp2.getValue();
System.out.println(map.get("info"));
更多使用方式查看官网:Language Reference :: Spring Framework