1.利用@ConfigurationProperties獲取配置的值,@ConfigurationProperties是springboot提供的基於安全類型的配置放置。java
application.propertiesredis
spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.maxIdle=10 spring.redis.maxActive=20
RedisConfig.javaspring
@Configuration @ConfigurationProperties(prefix = "spring.redis") //會在application,properties,查找spring.redis開頭的配置 public class RedisConfig { //必須有get set放入,不然值注入不進去 //匹配 spring.redis.host public String host; //匹配 spring.redis.port public int port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; }
2.利用@Value獲取值,在springboot中若是不配置@PropertySource(value="classpath:redis.properties")(配置文件路徑),默認是從application.properties中獲取值,你也能夠配置額外的@PropertySource,以下安全
@PropertySource(value="classpath:redis.properties") //@PropertySource(value="file:/home/config/redis.properties") public class RedisConfig { //從application.properties從獲取 @Value("${spring.redis.host}") public String host; //從application.properties從獲取 @Value("${spring.redis.port}") public int port; //從redis中獲取.properties從獲取 @Value("${name}") public String name; }
@ConfigurationPropertiesspringboot
爲springboot 專用的屬性注入屬性 文件名必須是application.properties/applicaiton.yml 默認爲全局文件中獲取這些熟悉值 app
@Value,this
value 屬性 處理能支持spel表達式之外 所有不如 ConfigurationPropertiesspa
@PropertySource.net
須要指定(classpath:xxxx.properties)加載指定的配置文件code
做者:盲目的拾荒者 來源:CSDN 原文:https://blog.csdn.net/niugang0920/article/details/80612070