天天看點

spring-boot-configuration-processor用法舉例

spring預設使用yml中的配置,但有時候要用傳統的xml或properties配置,就需要使用spring-boot-configuration-processor了

引入pom依賴

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
</dependency>      
author.name=zhangsan
author.age=20      

再在配置類開頭加上@PropertySource("classpath:your.properties"),其餘用法與加載yml的配置一樣

@Component
@PropertySource(value = {"classpath:static/config/authorSetting.properties"},
        ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties")
public class AuthorTest {
 
    @Value("${author.name}")
    private String name;
    @Value("${author.age}")
    private int age;
}      
@Component
@ConfigurationProperties(prefix = "author")
@PropertySource(value = {"classpath:static/config/authorSetting.properties"},
        ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties")
public class AuthorTest {
 
    private String name;
    private int age;
 
}      
@RestController
@EnableConfigurationProperties
public class DemoController {
 
    @Autowired
    AuthorTest authorTest;
 
    @RequestMapping("/")
    public String index(){
        return "author's name is " + authorTest.getName() + ",ahtuor's age is " + authorTest.getAge();
    }
}      

歡迎關注微信公衆号:大資料從業者

繼續閱讀