springEL和资源调用

本文使用spring 表达式语言实现资源的注入;

spring 主要在注解@Value的参数中使用表达式;

项目结构如图所示:


1)test.properties文件中的内容如下:

book.name = san guo yan yi
book.author = luo guan zhong


2)test.txt中的内容随便写


3)FunctionService中的代码如下:

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

public class FunctionService {
    
    @Value("在FunctionService中注入的值")
    private String other;
    
    public void sayHello() {
        System.out.println("hello,friendss");
    }

    public String getOther() {
        return other;
    }

    /*public void setOther(String other) {
        this.other = other;
    }
*/
    
}


4)ELConfig中的代码如下:

package com.dssp.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

@Configuration
@Component
// @PropertySource指定外部资源文件路径
@PropertySource("classpath:test.properties")
public class ELConfig {
    //注入普通字符串
    @Value("普通字符串")
    private String normal;
    
    // 注入操作系统属性
    @Value("#{systemProperties['os.name']}")
    private String osName;
    
    // 注入表达式结果
    @Value("#{T(java.lang.Math).random() * 100}")
    private long number;
    
    // 注入文件资源
    @Value("classpath:test.txt")
    private Resource testFile;
    
    // 注入网络资源
    @Value("http://www.baidu.com")
    private Resource testUrl;
    
    // 注入配置文件,注意使用的$
    @Value("${book.name}")
    private String bookName;
    
    @Value("${book.author}")
    private String bookAuthor;
    
    // 注入其他 bean属性,需提供该属性的getter方法
    @Value("#{functionService.other}")
    private String fromBean;

    @Autowired
    private Environment environment;

    public String getNormal() {
        return normal;
    }

    public String getOsName() {
        return osName;
    }

    public long getNumber() {
        return number;
    }

    public Resource getTestFile() {
        return testFile;
    }

    public Resource getTestUrl() {
        return testUrl;
    }

    public String getBookName() {
        return bookName;
    }

    public String getBookAuthor() {
        return bookAuthor;
    }

    public String getFromBean() {
        return fromBean;
    }

    public Environment getEnvironment() {
        return environment;
    }
    
    
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值