读取配置文件的两种方法
1、使用@PropertySource注解
配置文件jdbc.properties
配置类
@Configuration
@PropertySource(value= {"classpath:jdbc.properties"},ignoreResourceNotFound=false,encoding="UTF-8")
@ComponentScan("com.example")
public class Config {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/*
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
*/
public String getUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
测试代码
@Test
public void test1(){
AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(DoAnnoConfig.class);
Config config=ctx.getBean(Config.class);
System.out.print(config.getUsername());
}
测试结果

**@PropertySource可以传入一个文件,加载该文件下所有的.properties文件内容到Spring的配置项里,供Value注解使用。
**
2、使用Environment
配置类
@Configuration
@PropertySource(value= {"classpath:jdbc.properties"},ignoreResourceNotFound=false,encoding="UTF-8")
@ComponentScan("com.example")
public class Config1 {
@Autowired
private Environment env;
public void print1(){
System.out.print(env.getProperty("jdbc.username"));
}
}
测试函数
@Test
public void test2(){
AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(DoAnnoConfig.class);
Config1 config1=ctx.getBean(Config1.class);
config1.print1();
}
测试结果

Spring抽象了一个Environment来表示环境配置。
Spring 的Environment包含两方便的抽象,profile和 property。
前者是一组bean的定义,只有相应的profile被激活的情况下才会起作用。
后者是提供方便的抽象,应用程序可以方便的访问 system property 环境变量自定义属性等。
Spring的Environment可以方便的访问property属性,包含系统属性,环境变量和自定义的。
网友评论