Spring EL表达式语言获取配置文件中的属性

2025-10-31 05:38:09

1、Spring主要在注解@Value中使用表达式语言,该注解可以实现属性文件的注入 ,普通字符串的注入,操作系统属性的注入,表达式运算结果的注入,文件内容 的注入等,注入file文件需要添加commons-io包,我们还需要spring-boot的  父jar包。

<dependency>    <groupId>commons-io</groupId>    <artifactId>commons-io</artifactId>    <version>2.6</version></dependency>

<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.5.4.RELEASE</version></parent>

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>

Spring EL表达式语言获取配置文件中的属性

2、接下来我们创建一个test.properties文件,在该文件中添加两个属性,注意属性的写法为属性名=属性值。

Spring EL表达式语言获取配置文件中的属性

3、接下来我们创建一个需要被注入的Bean,此处我们演示普通字符串的注入,使用@Value注解,在类的属性上添加该注解,如下图所示。

Spring EL表达式语言获取配置文件中的属性

4、接下来我们编写配置类ElConfig,使用@Configuration注解标识这是一个配置类,使用@ComponentScan("el")注解声明扫包的路径,使用@PropertySource("classpath:test.properties")指定需要读取的配置文件的位置,若不指定则  下默认会从spring.properties文件中取。图中我们可以通过@Value注解注入普通字符串和从其他类中获取的字符串。

Spring EL表达式语言获取配置文件中的属性

5、我们也可以使用@Value注解获取操作系统属性,@Value("#{systemProperties['os.name']}")可以获取操作系统的名字,也可以使用@Value("#{T(java.lang.Math).random() * 100.0}")进行数学运算,甚至还可以注入URL如下图所示。

Spring EL表达式语言获取配置文件中的属性

6、使用下面的方法可以注入整个文件,可以将获取的文件打印出来。

@Value("classpath:test.properties")private Resource file;

System.out.println(IOUtils.toString(file.getInputStream(),"utf-8"));

7、接下来便是最重要的获取test.properties文件属性了,我们使用注解可以获取。@Value("${book.name}")private String bookName;

或者注入Environment,使用environment.getProperty("book.author")的方法获取到属性值。

@Autowiredprivate Environment environment;

Spring EL表达式语言获取配置文件中的属性

8、最后便是创建测试类,编写main方法进行启动,代码如下。

public class Test {    public static void main(String[] args) {        AnnotationConfigApplicationContext context =                new AnnotationConfigApplicationContext(ElConfig.class);        ElConfig config = context.getBean(ElConfig.class);        config.outputResource();        context.close();    }}

Spring EL表达式语言获取配置文件中的属性

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢