springboot默认会去你项目的src/main/resources目录下加载属性文件application.properties
属性文件如下:
book.name=Thanking in Java
book.author=Jack
book.price=78
Java代码如下:
@RestController
@EnableAutoConfiguration
public class SpringbootexampleApplication {
@Value("${book.name}")
private String bookName;
@Value("${book.author}")
private String bookAuthor;
@Value("${book.price}")
private double bookPrice;
@RequestMapping("/")
String index(){
return bookName + "|" + bookAuthor + "|" + bookPrice;
}
public static void main(String[] args) {
SpringApplication.run(SpringbootexampleApplication.class, args);
}
}
@Value注解用来注入配置属性
除了使用properties配件作为文件外,springboot还可以使用.yml文件来替代properties文件
YAML是JSON的超集,可以非常方便的指定层次结构的数据
book:
name: Thinking in Java
author: Jack
price: 89
采用如上所示的层次结构,就可以表示跟properties文件一样的效果
采用@Value注释注入属性值有的时候会显得很麻烦,特别是有多个属性值,比如上面的
@Value("${book.name}")
private String bookName;
@Value("${book.author}")
private String bookAuthor;
@Value("${book.price}")
private double bookPrice;
可以看到每个属性都需要单独进行注入,如果属性很多,就会很麻烦
@ConfigurationProperties注释可以实现属性配置与Bean的自动绑定,比如:
@Component
@ConfigurationProperties(prefix = "book")
public class Book {
private String name;
private String author;
private double 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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
@SpringBootApplication
public class SpringbootexampleApplication {
@Bean
@ConfigurationProperties(prefix = "book")
public Book book(){
return new Book();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootexampleApplication.class, args);
}
}
@RestController
@RequestMapping("/")
public class RootController {
@Autowired
private Book book;
@RequestMapping("/book")
public String index(){
return book.getName() + "|" + book.getAuthor() + "|" + book.getPrice();
}
}
这样就可以实现,属性配置值与Bean的自动绑定
@ConfigurationProperties的校验
@Component
@ConfigurationProperties(prefix = "book")
@Validated
public class Book {
@NotNull
private String name;
private String author;
private double 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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
在Bean上加@Validated注释,在属性name上加@NotNull表示name属性不能为null
假如你的属性文件或yml文件里面没有配置book.name属性,项目启动就会给出校验的提示
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'book' to com.example.demo.Book failed:
Property: book.name
Value: null
Reason: 不能为null