方式一:使用配置类
Demo1:
如灵活配置一个数字4:
在application.properties中:
app.calculate_period=${APP_CALCULATE_PERIOD:4}
代码:
Configuration配置类
@Configuration
@ConfigurationProperties("app")
@Validated
public class AppProperties {
@NotNull
private Integer calculatePeriod;
public Integer getCalculatePeriod() {
return calculatePeriod;
}
public void setCalculatePeriod(Integer calculatePeriod) {
this.calculatePeriod = calculatePeriod;
}
}
使用:
// 1. Calculate period(default 4 years)
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.YEAR, -appProperties.getCalculatePeriod());
Demo2:
》配置一个Book类
在src/main/resources文件夹下创建文件book.properties
book.name=红楼梦
book.author=曹雪芹
book.price=28
》创建Book Bean,并注入properties文件中的值
@Component
@ConfigurationProperties(prefix = "book",locations = "classpath:book.properties")
public class BookBean {
private String name;
private String author;
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
prefix是指前缀,location指定要注入文件的位置。
》使用
在Controller中添加如下代码注入Bean:
@Autowired
private BookBean bookBean;
@RequestMapping("/book")
public String book() {
return "Hello Spring Boot! The BookName is "+bookBean.getName()+";and Book Author is "+bookBean.getAuthor()+";and Book price is "+bookBean.getPrice();
}
方式二:直接使用@value取值
application.properties配置文件中:
spring.application.name=appxxx
代码中,直接可以使用@value获取为类的对应属性值
@Value("${spring.application.name}")
String appId;