SpringBoot custom configuration item
Spring Boot built-in configuration items is far from supporting our program is running, when the project design, often because of the need to expand the project need to set aside a number of custom settings, Spring Boot allows us to configure custom options.
Learning Video: http://www.itlaoqi.com/chapter/1685.html
Source Address: QQ group 814,077,650, self-help group sharing download
Old Qi official website: itlaoqi.com (in which more dry)
In Spring Boot, there are two ways to use the Custom option
- @Value single attribute injection
@ConfigurationProperties type-safe load
The first: @Value single attribute injection
Create a configuration config.properties
app.name=demoapp
app.version=1.0.0
app.description=demoapp description
app.page-size=20
app.show-advert=true
app.website=http://www.itlaoqi.com
Load configuration files on startup
@SpringBootApplication
//在入口类启动时加载config.properties
@PropertySource("classpath:config.properties")
public class MyspringbootApplication {
public static void main(String[] args) {
// SpringApplication.run(MyspringbootApplication.class, args);
SpringApplication app = new SpringApplication(MyspringbootApplication.class);
//关闭Banner
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
}
@Value dynamic injection
@Controller
public class MyController {
@Value("${app.name}")
private String name;
@Value("${app.page-size}")
private Integer pageSize;
...
The second: @ConfigurationProperties
@Component
//将所有app前缀的属性自动赋值给对应Bean 属性
@ConfigurationProperties(prefix="app")
public class AppConfig {
private String name;
private String description;
private String version;
private Integer pageSize;
private Boolean showAdvert;
private String website;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
...
When using dynamic injection
@Controller
public class MyController {
//动态注入IOC容器中匹配的Bean
@Resource //相同功能可使用@Autowire
private AppConfig appConfig;
...