一 点睛
Spring EL-Spring表达式语言,支持在xml和注解上使用表达式,类似JSP的EL表达式语言。
Spring开发中经常涉及调用各种资源的情况,包含普通文件、网址、配置文件、系统环境变量等,我们可以使用Spring表达式语言实现资源的注入。
Spring主要在注解@Value的参数中使用表达式。
二 实战
演示Spring EL在以下几种情况下使用:
- 注入普通字符
- 注入操作系统属性
- 注入表达式运算结果
- 注入其他Bean的属性
- 注入文件内容
- 注入网址内容
- 注入属性文件
1 准备,增加commons-io依赖,该依赖可简化文件相关操作,使用commons-io将file转换成字符串
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
2 准备test.txt文件,内容如下
test file
3 准备test.properties,内容如下
book.author=wangyunfei
book.name=spring boot
4 编写需要注入的Bean
package com.wisely.highlight_spring4.ch2.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Value("other class property") //注入普通字符串
private String another;
public String getAnother() {
return another;
}
public void setAnother(String another) {
this.another = another;
}
}
5 编写配置类
package com.wisely.highlight_spring4.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.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.spr