干货直接上:
一、使用注解@Value
@Value("${userBucket.path}")
private String userBucketPath;
二、使用Environment
// 1、注入Environment
@Autowired
private Environment env;
……
env.getProperty("user-customer.path");
……
这种方法在以下情况比方法1更方便:
1、当需要动态拼装多个参数时;
2、当参数名称是动态变化时;
3、当你需要判断这个参数是不是真的存在时,这是可以用env.getRequiredProperty("user-customer.path")
替代,如果不存在将会抛出异常:
IllegalStateException: Required key 'user-cdustomer.path' not found
注:导入的Environment
一定是org.springframework.core.env.Environment
,千万别弄错!
三、使用注解@ConfigurationProperties
和@Configuration
@ConfigurationProperties(prefix = "user-customer")
@Configuration
public class CustomerConfiguration {
private String path;
// Getters and Setters go here
}
然后在使用的时候注入即可:
@Autowired
private CustomerConfiguration config;
……
config.getPath();
……
四、使用注解@PropertySource
配合Environment
使用注解@PropertySource
配合Environment
这个方法是很强大的,注解@PropertySource可以读取一个或者多个配置文件,可以读取指定位置的配置文件,实在是居家旅行必备良药~~~~
1、我们首先在resource中建立一个spring文件夹,然后放入一个叫config.properties
的配置文件,内容如下:
ds.user=admin
2、然后创建一个配置Bean
@Configuration
@PropertySource(value = "classpath:spring/config.properties")
public class ConfigPropertySource {
@Autowired
private Environment env;
public String getUser() {
return env.getProperty("ds.user");
}
}
3、最后在使用的地方注入该配置Bean即可
@Autowired
private ConfigPropertySource configPropertySource;
……
configPropertySource.getUser();
……
注1:当需要访问多配置文件时,需要用到注解@PropertySources
,这个写法先不写了,后面再开新帖描述,免得篇幅过长。
注2:@PropertySource
配合@Value
也是可以的,如:
@Component
@PropertySource(value = "classpath:spring/config.properties")
public class SomeComponent {
@Value("${ds.user}")
private String user;
}