Spring读取外部的资源配置文件—@PropertySource和@Value实现资源文件配置
通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值;
@PropertySource注解主要是让Spring的Environment接口读取属性配置文件用的,标识在@Configuration配置类上;
@Value注解可以用在字段和方法上,通常用于从属性配置文件中读取属性值,也可以设置默认值。
具体用法:
@PropertySource(value = { "classpath:config.properties" }, ignoreResourceNotFound = true) public class UserSpringConfig { ... }
a、配置多个配置文件
@PropertySource(value = { "classpath:jdbc.properties", "classpath:config.properties"}) public class UserSpringConfig { ... }
b、忽略不存在的配置文件
@PropertySource(value = { "classpath:jdbc.properties","classpath:config.properties"}, ignoreResourceNotFound = true) public class UserSpringConfig { ... }
资源文件配置示例
1、创建配置文件,${project}/src/main/resources/config.properties
username=zhangsan password=123456 age=20
2、读取外部的资源配置文件
package com.lynch.javaconfig; import org.springframework.beans.factory.annotation.Value; public class User { @Value("${username}") private String username; @Value("${password}") private String password; @Value("${age}") private Integer age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [username=" + username + ", password=" + password + ", age=" + age + "]"; } }
3、编写SpringConfig,用于实例化Spring容器
package com.lynch.javaconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; //通过@Configuration注解来表明该类是一个Spring的配置,相当于一个xml文件 @Configuration @ComponentScan(basePackages = "com.lynch.javaconfig") @PropertySource(value = { "classpath:config.properties"}, ignoreResourceNotFound = true) public class UserSpringConfig { @Bean public User user(){ return new User(); } }
4、编写测试方法,用于启动Spring容器
package com.lynch.javaconfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class UserApplication { public static void main(String[] args) { // 通过Java配置来实例化Spring容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserSpringConfig.class); System.out.println(context.getBean(User.class)); // 销毁该容器 context.destroy(); } }
5、执行结果
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. User [username=Administrator, password=123456, age=20] 九月 16, 2018 9:04:45 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
注意,从执行结果发现username输出的是"Administrator",而不是"zhangsan",那是因为系统变量跟配置文件存在相同变量时,优先从系统变量获取,故username输出的是"Administrator"。