在项目中为了灵活配置,我们常采用配置文件,常见的配置文件就比如xml和properties,springboot允许使用properties和yaml文件作为外部配置。现在编译器对于yaml语言的支持还不够好,目前还是使用properties文件作为外部配置。
1、 常规属性配置
- 新建springboot项目
- 引入web模块
- 在application.properties文件中加入配置
book.name=zhangcheng
book.age=66
- 新建测试类
@RestController
@SpringBootApplication
public class PropertiesApplication {
@Value("${book.name}")
private String name;
@Value("${book.age}")
private Long age;
@RequestMapping("/pros")
public String index() {
return "book.name:" + name + " book.age:" + age;
}
public static void main(String[] args) {
SpringApplication.run(PropertiesApplication.class, args);
}
}
- 使用value注解引入配置信息
- 启动项目
从配置文件中可以得到信息。
2、配置类型安全的配置
有两种配置方式,一种是采用默认的配置,就是再application.properties配置文件中进行配置
另一种是自己定义配置文件,在配置类中指定目录即可
- 第一种
配置文件不变 - 新建配置文件类
@Component
@ConfigurationProperties(prefix = "book")
public class AuthorSettings {
private String name;
private Long age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
-
@ConfigurationProperties(prefix = "book")注解指定前缀,然后属性值要和配置文件中的字段保持一致
例如book.name我们使用了前缀book,那么我们就要将属性值设为name,否则找不到属性。 -
第二种 - 自定义配置类
-
新建配置文件
book.name=zhangcheng
book.age=55
在注解上加入locations注解:@ConfigurationProperties(prefix = "book", locations = {"classpath:config/author.properties"})
指定路径。
- 在使用的时候注解注入就可以了
@RestController
@SpringBootApplication
public class Chapter61Application {
@Autowired
private AuthorSettings authorSettings;
@RequestMapping("/")
public String index() {
return "book.name:" + authorSettings.getName() + "book.age:" + authorSettings.getAge();
}
public static void main(String[] args) {
SpringApplication.run(Chapter61Application.class, args);
}
}
Paste_Image.png