赞
踩
Spring开发中经常设计调用各种资源的情况,包括普通文件,网址、配置文件、系统环境变量等,可以使用Spring的表达式语言实现资源的注入。
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();
}
}
idea
中,配置文件需放在根目录下的resources
目录中,或者其他单独设置的资源目录,否则会报无法找到该文件的错误springboot
中仍然适用,Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。