有時候有這樣子的情景,咱們想把配置文件的信息,讀取並自動封裝成實體類,這樣子,咱們在代碼裏面使用就輕鬆方便多了,這時候,咱們就能夠使用@ConfigurationProperties,它能夠把同類的配置信息自動封裝成實體類java
首先在配置文件裏面,這些信息是這樣子滴app
connection.username=admin connection.password=kyjufskifas2jsfs connection.remoteAddress=192.168.1.1
這時候咱們能夠定義一個實體類在裝載配置文件信息this
@Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings { private String username; private String remoteAddress; private String password ; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(String remoteAddress) { this.remoteAddress = remoteAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
咱們還能夠把@ConfigurationProperties還能夠直接定義在@bean的註解上,這是bean實體類就不用@Component和@ConfigurationProperties了code
@SpringBootApplication public class DemoApplication{ //... @Bean @ConfigurationProperties(prefix = "connection") public ConnectionSettings connectionSettings(){ return new ConnectionSettings(); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
而後咱們須要使用的時候就直接這樣子注入rem
@RestController @RequestMapping("/task") public class TaskController { @Autowired ConnectionSettings conn; @RequestMapping(value = {"/",""}) public String hellTask(){ String userName = conn.getUsername(); return "hello task !!"; } }
若是發現@ConfigurationPropertie不生效,有多是項目的目錄結構問題,get
你能夠經過@EnableConfigurationProperties(ConnectionSettings.class)來明確指定須要用哪一個實體類來裝載配置信息it
@Configuration @EnableConfigurationProperties(ConnectionSettings.class) public class MailConfiguration { @Autowired private MailProperties mailProperties; @Bean public JavaMailSender javaMailSender() { // omitted for readability } }