@PropertySource(“classpath:config.properties”) :指定文件的地址
ELConfig .java
package com.netant.EL;
import java.io.IOException;
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.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.netant.EL")
@PropertySource("classpath:config.properties") //
public class ELConfig {
@Value("you had a bad day") // 注入普通字符串
private String normal;
@Value("#{systemProperties['os.name']}") // 注入操作系统属性
private String osName;
@Value("#{T(java.lang.Math).random() * 100.0}") // 注入表达式结果
private double randomNumber;
@Value("#{demoService.another}") // 注入其他Bean属性
private String fromAnother;
@Value("classpath:test.txt") // 注入文件资源
private Resource testFile;
@Value("https://www.baidu.com/?tn=57095150_1_oem_dg") // 注入网址资源
private Resource testUrl;
@Value("${jdbc.type}") // 注入配置文件
private String dataBaseType;
@Autowired
private Environment environment; // 注入Properties还可以从Environment中获取
// 若使用@Value注入,则要配置一个 PropertySourcesPlaceholderConfigurer 的Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
return new PropertySourcesPlaceholderConfigurer();
}
public void outputResource() throws IOException{
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(dataBaseType);
System.out.println(environment.getProperty("jdbc.driver"));
}
}
Main.java
package com.netant.EL;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ELConfig.class);
ELConfig eLConfig = context.getBean(ELConfig.class);
eLConfig.outputResource();
context.close();
}
}