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

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

项目结构如图所示:

springEL和资源调用


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;
    }
    
    
}
 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-09
  • 2021-11-19
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
猜你喜欢
  • 2021-08-25
  • 2021-12-07
  • 2021-09-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案