Spring中使用注解@Value读取xx.properties配置文件信息

Spring中使用注解@Value读取xx.properties配置文件信息


1. 介绍

Spring开发中经常设计调用各种资源的情况,包括普通文件,网址、配置文件、系统环境变量等,可以使用Spring的表达式语言实现资源的注入。

  • 示例中演示:注入普通字符、系统属性、表达式运算结果、其他bean的属性,文件、网站内容、属性文件

2. 示例代码

  • EIConfig.java配置类


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.xzp.ch1_2_3.ch2.el")
@PropertySource("classpath:ch2/test.properties")  //属性文件需放在根目录的resources文件夹下面,才能被读取出来
public class ElConfig {

    @Value("I Love You!") //1
    private String normal;

    @Value("#{systemProperties['os.name']}") //2
    private String osName;

    @Value("#{ T(java.lang.Math).random() * 100.0 }") //3
    private double randomNumber;

    @Value("#{demoService.another}") //4 其他bean,此处未列出代码
    private String fromAnother;

    @Value("classpath:ch2/test.txt") //5 其他的普通文本文件
    private Resource testFile;

    @Value("http://www.baidu.com") //6
    private Resource testUrl;

    @Value("${book.name}") //7
    private String bookName;

    @Autowired
    private Environment environment; //7

    @Bean //7
    public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
        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(IOUtils.toString(testFile.getInputStream()));
            System.out.println(IOUtils.toString(testUrl.getInputStream()));
            System.out.println(bookName);
            System.out.println(environment.getProperty("book.author"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
  • 配置文件test.properties
book.author=wangyunfei
book.name=spring boot
  • 使用示例主函数Main.java
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();
    }
}


3. 注意问题

  • idea中,配置文件需放在根目录下的resources目录中,或者其他单独设置的资源目录,否则会报无法找到该文件的错误
  • 在读取配置文件的方法,在springboot中仍然适用,

猜你喜欢

转载自blog.csdn.net/u011857433/article/details/80144391