Spring EL 和资源调用




文章目录

  • 1.概述
  • 2.添加支持
  • 4.新建包和相关文件
  • 4.完善各个类
  • 5.测试






1.概述

Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似于JSP的EL表达式语言。
Spring开发中经常涉及调用各种资源的情况,包含普通文件、网址、配置文件、系统环境变量等,我们可以使用Spring的表达式语言实现资源的注入。
Spring主要在注解@Value的参数中使用表达式。
本节演示实现以下几种情况:
(1)注入普通字符;
(2)注入操作系统属性;
(3)注入表达式运算结果;
(4)注入其他Bean的属性;
(5)注入文件内容;
(6)注入网址内容;
(7)注入属性文件。

下面我们将通过一个例子来对上面的各个情况进行一个实战





2.添加支持

由于在测试中,涉及到对文件内容的读取。因此为了简化与文件相关的操作,我们需要添加一个commons-io的依赖(在测试中,通过使用commons-io将file转换为字符串)。代码如下:

<!-- commons-io 支持 -->
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.3</version>
</dependency>





4.新建包和相关文件

这里我们需要在"src/main/java/com/study/spring/“下建立一个新的包"ch2.el”,然后再在这个包中新建一个test.txt文档,内容随意。我写的内容如下:

this is a test file
and this is the second row

同时,还需要新建一个文件test.properties,内容如下:

property.author=zed
property.name=spring study

最后再新建3个类,结构如下图所示:

spring el表达式取对象属性 spring注解支持el表达式_Spring EL 和资源调用

4.完善各个类

首先是类DemoService(需要呗注入的测试Bean),其内容如下:

package com.study.spring.ch2.el;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class DemoService {
    @Value("其他类属性")         //注入普通字符串
    private String another;

    public String getAnother() {
        return another;
    }

    public void setAnother(String another) {
        this.another = another;
    }
}

然后是配置类ElConfig,其内容如下:

package com.study.spring.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.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

@Configuration
@ComponentScan("com.study.spring.ch2.el")
@PropertySource("classpath:com/study/spring/ch2/el/test.properties")    //注入配置文件需要使用@PropertySource指定文件地址
public class ElConfig {
    @Value("Hellow Spring!")                        //注入普通字符串
    private String normal;

    @Value("#{systemProperties['os.name']}")        //注入操作系统属性
    private String osName;

    @Value("#{ T(java.lang.Math).random() * 100}")  //注入表达式结果
    private double randomNumber;

    @Value("#{demoService.another}")                //注入其他Bean属性
    private String fromAnother;

    @Value("classpath:com/study/spring/ch2/el/test.txt")//注入文件资源
    private Resource testFile;

    @Value("http://www.baidu.com")                  //注入网址信息
    private Resource testUrl;

    @Value("${property.name}")                          //注入配置文件
    private String propertyName;

    @Autowired
    private Environment environment;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer(){    //使用@Value注入需要配置PropertySourcesPlaceholderConfigurer的Bean
        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(testFile);
            System.out.println(IOUtils.toString(testFile.getInputStream()));
            System.out.println(IOUtils.toString(testUrl.getInputStream()));
            System.out.println(propertyName);
            System.out.println(environment.getProperty("property.author"));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

特别注意:注入配置配件需使用@PropertySource指定文件地址,若使用@Value注入,则要配置一个PropertySourcesPlaceholderConfigurer的Bean。
最后是测试主类Main,其内容如下:

package com.study.spring.ch2.el;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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





5.测试

我们选择刚刚建立的测试主类Main文件,右键,在弹出的窗体中选择"Run",效果如下:

spring el表达式取对象属性 spring注解支持el表达式_spring el表达式取对象属性_02


我们发现程序报错:“class path resource [com/study/spring/ch2/el/test.properties] cannot be opened because it does not exist”.

报错的点是:com/study/spring/ch2/el/test.properties这个文件不在,但是我们看图这个文件确实是存在的啊,并且在@PropertySource注解中指定的地址确实没错:

spring el表达式取对象属性 spring注解支持el表达式_Spring Boot_03


再仔细查看错误信息:“class path resource [com/study/spring/ch2/el/test.properties] cannot be opened because it does not exist”,它说的是"class path resource" ,是在resource文件下查找的。

此时我们看resources文件夹,整个都为空,那在resource文件夹当然下没有com/study/spring/ch2/el/test.properties这个文件。因此当我在resource下创建此目录与文件后(com/study/spring/ch2/el/test.properties),再次执行就可以运行了。此时得到的结果如下:

spring el表达式取对象属性 spring注解支持el表达式_Spring 基础_04


解释一下出现上述情况的原因:Spring Boot的资源文件默认是放在src/main/resources下的。我在用相对路径访问这些资源文件时,其默认是去resources文件下进行扫描,因此最初我将这些资源文件放在/src/main/java下时其并不能找到这些文件,所以就报了java.io.FileNotFoundException的错。