Spring EL和资源调用

一 点睛

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值