springboot實現將配置檔案的屬性轉換成一個對應的pojo物件的屬性
阿新 • • 發佈:2019-01-10
1.首先你需要在application.yml(如果是application.properties也差不多)配置檔案配置相應的屬性資訊,例如
loginType: person: 1 vcode: 232.在pom檔案加入下面的依賴
3.寫一個相應的pojo類,注意prefix後面的需要寫你自己的<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
@ConfigurationProperties(prefix = "myProperties.loginType")
package com.suiyu.account.properties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author yedeguo * @date 2017/8/24 */ @ConfigurationProperties(prefix = "loginType") public class LoginTypeProperties { private String person; private String vcode; public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public String getVcode() { return vcode; } public void setVcode(String vcode) { this.vcode = vcode; } public LoginTypeProperties() { } public LoginTypeProperties(String person, String vcode) { this.person = person; this.vcode = vcode; } @Override public String toString() { return "LoginTypeProperties{" + "person='" + person + '\'' + ", vcode='" + vcode + '\'' + '}'; } }
4.在springboot的入口main方法加上下面的這個註解,括號裡面的寫你自己的pojo類@EnableConfigurationProperties(LoginTypeProperties.class)
@SpringBootApplication @EnableConfigurationProperties(LoginTypeProperties.class) public class AccountApplication { public static void main(String[] args) { SpringApplication.run(AccountApplication.class,5.然後就可以在相應的Controller層或者其他地方@Autowired進來,至此大功告成args); } }
@Autowired private LoginTypeProperties loginTypeProperties;