- 使用@Value("${property}")注解注入配置屬性有時(shí)可能比較笨重扎狱,特別是需要使用多個(gè)properties或你的數(shù)據(jù)本身有層次結(jié)構(gòu)。為了控制和校驗(yàn)?zāi)愕膽?yīng)用配置匠抗,Spring Boot提供一個(gè)允許強(qiáng)類(lèi)型beans的替代方法來(lái)使用properties汞贸。
示例:
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private InetAddress remoteAddress;
// ... getters and setters
}
-
當(dāng)@EnableConfigurationProperties注解應(yīng)用到你的@Configuration時(shí)印机,任何被@ConfigurationProperties注解的beans將自動(dòng)被Environment屬性配置。這種風(fēng)格的配置特別適合與SpringApplication的外部YAML配置進(jìn)行配合使用多柑。
# application.yml connection: username: admin remoteAddress: 192.168.1.1 # additional configuration as required
-
為了使用@ConfigurationProperties beans竣灌,你可以使用與其他任何bean相同的方式注入它們。
@Service public class MyService { @Autowired private ConnectionSettings connection; //... @PostConstruct public void openConnection() { Server server = new Server(); this.connection.configure(server); } }
-
你可以通過(guò)在@EnableConfigurationProperties注解中直接簡(jiǎn)單的列出屬性類(lèi)來(lái)快捷的注冊(cè)@ConfigurationProperties bean的定義初嘹。
@Configuration @EnableConfigurationProperties(ConnectionSettings.class) public class MyConfiguration { }
注:使用@ConfigurationProperties能夠產(chǎn)生可被IDEs使用的元數(shù)據(jù)文件。
第三方配置
正如使用@ConfigurationProperties注解一個(gè)類(lèi)豁生,你也可以在@Bean方法上使用它漫贞。當(dāng)你需要綁定屬性到不受你控制的第三方組件時(shí)迅脐,這種方式非常有用豪嗽。
-
為了從Environment屬性配置一個(gè)bean,將@ConfigurationProperties添加到它的bean注冊(cè)過(guò)程:
@ConfigurationProperties(prefix = "foo") @Bean public FooComponent fooComponent() { ... }
和上面ConnectionSettings的示例方式相同隐锭,任何以foo為前綴的屬性定義都會(huì)被映射到FooComponent上计贰。
松散的綁定(Relaxed binding)
-
Spring Boot使用一些寬松的規(guī)則用于綁定Environment屬性@ConfigurationProperties beans,所以Environment屬性名和bean屬性名不需要精確匹配荞怒。常見(jiàn)的示例中有用的包括虛線分割(比如褐桌,context--path綁定到contextPath)和將環(huán)境屬性轉(zhuǎn)為大寫(xiě)字母(比如象迎,PORT綁定port)。
示例:@Component @ConfigurationProperties(prefix="person") public class ConnectionSettings { private String firstName; }
下面的屬性名都能用于上面的@ConfigurationProperties類(lèi):
屬性 | 說(shuō)明 |
---|---|
person.firstName | 標(biāo)準(zhǔn)駝峰規(guī)則 |
person.first-name | 虛線表示啦撮,推薦用于.properties和.yml文件中 |
PERSON_FIRST_NAME | 大寫(xiě)形式拇舀,使用系統(tǒng)環(huán)境變量時(shí)推薦 |
@ConfigurationProperties校驗(yàn)
-
Spring Boot將嘗試校驗(yàn)外部的配置,默認(rèn)使用JSR-303(如果在classpath路徑中)聘鳞。你可以輕松的為你的@ConfigurationProperties類(lèi)添加JSR-303 javax.validation約束注解:
@Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings { @NotNull private InetAddress remoteAddress; // ... getters and setters }
你也可以通過(guò)創(chuàng)建一個(gè)叫做configurationPropertiesValidator的bean來(lái)添加自定義的Spring Validator。
注:spring-boot-actuator模塊包含一個(gè)暴露所有@ConfigurationProperties beans的端點(diǎn)站楚。簡(jiǎn)單地將你的web瀏覽器指向/configprops或使用等效的JMX端點(diǎn)搏嗡。具體參考Production ready features。