Spring Expression Language (SpEL),支持在xml和注解中使用表达式。
官方文档:https://docs.spring.io/spring-framework/docs/5.0.x/spring-framework-reference/core.html#expressions
Spring开发中经常涉及调用各种资源的情况,包含普通文件、网址、配置文件、系统环境变量等。我们可以使用Spring的表达式语言实现资源的注入。
Spring主要在注解@Value的参数中使用表达式。
1. 注入普通字符;
2. 注入操作系统属性;
3. 注入表达式运算结果;
4. 注入其他bean的属性;
5. 注入文件内容;
6. 注入网址内容;
7. 注入属性文件。
下面给出一个例子:
可通过加入commons-io来简化文件的相关操作。
package com.vic.highlight_spring5.ch2.el;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
public class ELConfig {
@Value("I love this.")
private String normal;
@Value("#{systemProperties['os.name']}")
private String osName;
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber;
@Value("#{demoService.another}")
private String fromAnother;
@Value("classpath:com/vic/highlight_spring5/ch2/el/test.txt")
private Resource testFile;
@Value("http://www.baidu.com")
private Resource testUrl;
@Value("${project.name}")
private String projectName;
@Autowired
private Environment environment;
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public void outputResource() {
try{
System.out.println(normal);
System.out.println(osName);
System.out.println(randomNumber);
System.out.println(fromAnother);
System.out.println(IOUtils.toString(testFile.getInputStream()));
System.out.println(IOUtils.toString(testUrl.getInputStream()));
System.out.println(projectName);
System.out.println(environment.getProperty("project.author"));
} catch (Exception e) {
e.printStackTrace();
}
}
}