Spring中Properties相關注解
阿新 • • 發佈:2020-10-20
1、@PropertiesSource註解
這是Spring中的註解,用於讀取屬性檔案,預設讀取classpath下的檔案。
如在classpath路徑下的a.properties中:
desc="is a property"
通過Value註解可以去到屬性:
@Component @PropertySource("classpath:a.properties") public class Config { @Value("${desc}") String desc; public void print(){ System.out.println(desc); } }
也可以通過@PropertiesSources註解一次讀取多個配置檔案。
2、@ConfigurationProperties註解
這是SpringBoot中的註解,使用這個註解需要一個依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
在application.yml下有以下屬性:
這在Bean中其實是可以直接拿到的,因為該檔案自動被SpringBoot載入。
server:
port: 8099
com:
other: "通過註解獲取"
通過@Value註解是可以直接拿到屬性的,如☆處直接拿到yml的資料。
而◆處不需要註解,通過@ConfigurationProperties(prefix = "com")註解拿到other資料。
當然必須要有該屬性的set方法,所以這適合在JavaBean中使用。
@Component @PropertySource("classpath:a.properties") @ConfigurationProperties(prefix = "com") public class Config { @Value("${server.port}") //☆ String port; @Value("${desc}") String desc; String other;//◆ public String getOther() { return other; } public void setOther(String other) { this.other = other; } public void print(){ System.out.println(port+desc+other); } }