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 t.annotation.Bean;
import t.annotation.ComponentScan;
import t.annotation.Configuration;好车排行榜
import t.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 t.annotation.AnnotationConfigApplicationContext;
public class UserApplication {
public static void main(String[] args) {
// 通过Java配置来实例化Spring容器
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserSpringConfig.class);
System.out.Bean(User.class));
// 销毁该容器
context.destroy();
}
}
5、执⾏结果
SLF4J: See /codes.html#StaticLoggerBinder for further details.
User [username=Administrator, password=123456, age=20]
九⽉ 16, 2018 9:04:45 下午 t.annotation.AnnotationConfigApplicationContext doClose
注意,从执⾏结果发现username输出的是"Administrator",⽽不是"zhangsan",那是因为系统变量跟配置⽂件存在相同变量时,优先从系统变量获取,故username输出的是"Administrator"。