
Spring Boot - Auto Configuration
2021, Aug 28
Tạo lớp configuration và tự động load từ file trong Spring Boot
- Thêm configuration trong file application.yml
my-config:
id: 1
value: my value
- Tạo class tương ứng với configuration
public class MyConf {
public int id;
public String value;
}
- Sử dụng annotation @Configuration, @ConfigurationProperties và các hàm setter để Spring Boot biết và tự động tạo bean tương ứng
@Setter
@Configuration
@ConfigurationProperties(prefix = "my-config")
public class MyConf {
//...
}
- Sử dụng bean MyConf thông qua annotation Autowired
@Autowired
MyConf myConf;
...
System.out.println("Id: " + myConf.getId());
System.out.println("Value: " + myConf.getValue());
Output
Id: 1
Value: my value
Source code ở đây