@ConfigurationProperties與@Value進行屬性的注入
阿新 • • 發佈:2018-11-20
ConfigurationProperties
@ConfigurationProperties 是spring-boot中特有的註解。
使用場景如下:
假設application.properties 檔案存在redis配置如下:
redis.config.maxTotal=5000 redis.config.maxIdle=10 redis.config.maxWaitMillis=5000 redis.config.testWhileIdle=true redis.config.numTestsPerEvictionRun=100 redis.config.timeBetweenEvictionRunsMillis=6000 redis.config.testOnBorrow=true redis.config.testOnReturn=true redis.config.host=127.0.0.1 redis.config.port=6379 redis.config.name=localhost_redis redis.config.timeout=5000 redis.config.weight=1 redis.config.password=XXX
在定義的Redis配置類中:
@Configuration @ConfigurationProperties(prefix = "redis.config") @Data public class RedisConfiguration { private int maxTotal; private int maxIdle; private int maxWaitMillis; private boolean testWhileIdle; private int numTestsPerEvictionRun; private int timeBetweenEvictionRunsMillis; private boolean testOnBorrow; private boolean testOnReturn; private String host; private String name; private int port; private int timeout; private int weight; private String password; }
// @ConfigurationProperties(prefix = “redis.config”) 這個註解,可以使屬性檔案中的值和類中的屬性對應起來。
注意:在spring boot中除了使用這個註解讀取屬性檔案值外,還可以是用@Value註解。
@Value(“${spring.redis.weight}”)
private int weight;
@Value
Spring開發過程中經常遇到需要把特殊的值注入到成員變數裡,比如普通值、檔案、網址、配置資訊、系統 變數等等。Spring主要使用註解@Value把對應的值注入到變數中。
常用的注入型別有以下幾種:
- 注入普通字串。
- 注入作業系統屬性。
- 注入表示式運算結果。
- 注入其他bean的屬性。
- 注入檔案內容。
- 注入網址資訊。
- 注入屬性檔案。
具體可以參考@Value註解