1. 使用 ConfigurationProperties
來使用 properties
的值。
- 啟用自定義配置:
@Configuration @EnableConfigurationProperties({YourConfigClass}.class)
@ConfigurationProperties(prefix)
註解自定義的YourConfigClass
- 通過
bean
來使用自定義的配置資訊類
@SpringBootApplication
@EnableConfigurationProperties(TestConfigurationProperties.class)
public class DemoApplication{
@Autowired
TestConfigurationProperties testConfig;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
new DemoApplication().testConfig.printProperties();
}
@PostConstruct
private void init(){
testConfig.printProperties();
}
}
複製程式碼
@ConfigurationProperties("testconfig")
public class TestConfigurationProperties {
private String first;
private String second;
private String third;
private String fourth;
private String fifth;
private String sixth;
private String seventh;
private String eightth;
//getters and setters
複製程式碼
這樣就可以通過 Bean
來使用。
2. 通過 @Value
使用
通過註解 @Value("${testconfig.first}")
可以給變數賦值成 配置 testconfig.first
的資訊。
@Component
public class TestValue {
@Value("${testconfig.first}")
private String first;
@Value("${testconfig.second}")
private String second;
@Value("${testconfig.third}")
private String third;
@Value("${testconfig.fourth}")
private String fourth;
@Value("${testconfig.fifth}")
private String fifth;
@Value("${testconfig.sixth}")
private String sixth;
@Value("${testconfig.seventh}")
private String seventh;
@Value("${testconfig.eightth}")
private String eightth;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public String getFourth() {
return fourth;
}
public void setFourth(String fourth) {
this.fourth = fourth;
}
public String getFifth() {
return fifth;
}
public void setFifth(String fifth) {
this.fifth = fifth;
}
public String getSixth() {
return sixth;
}
public void setSixth(String sixth) {
this.sixth = sixth;
}
public String getSeventh() {
return seventh;
}
public void setSeventh(String seventh) {
this.seventh = seventh;
}
public String getEightth() {
return eightth;
}
public void setEightth(String eightth) {
this.eightth = eightth;
}
public void printProperties(){
System.out.println("\ntest value:");
System.out.println("first: " + first);
System.out.println("second: " + second);
System.out.println("third: " + third);
System.out.println("fourth: " + fourth);
System.out.println("fifth: " + fifth);
System.out.println("sixth: " + sixth);
System.out.println("seventh: " + seventh);
System.out.println("eightth: " + eightth);
}
}
複製程式碼
輸出為:
test value:
first: ./config/
second: ./config/yml
third: classpath/config/
fourth: classpath
fifth: ./config/
sixth: ./config/
seventh: ./config/
eightth: ./config/
複製程式碼