1、常规属性配置
(1)在application.properties增加属性
server.port=9090
server.context-path=/helloboot
book.author=zxy
book.name=spring boot
(2)修改入口类
@Value("${book.author}")
private String author;
@Value("${book.name}")
private String name;
@RequestMapping("/")
String index(){
return "hello Spring Boot"+author+" "+name;
}
(3)访问http://localhost:9090/helloboot
hello Spring Bootzxy spring boot
2、(类型安全配置)基于properties
@Value注入在实际项目显得麻烦,配置通常是多个,
(1)添加配置,在项目资源路径下新建author.properties
author.name=zxy11
author.age=20
(2)新建包com.wisely.config,此包下新建类AuthorSettings
boot1.5以前添加文件是在@ConfigurationProperties里面的lications指定 ,这儿是1.5以上的版本,方法是在PropertySource指定
@Component
@PropertySource("classpath:author.properties")
@ConfigurationProperties(prefix = "author")
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;
}
}
(3)检验代码
@SpringBootApplication
@RestController
public class ZXYApplication {
@Autowired
private AuthorSettings authorSettings;
@RequestMapping("/")
public String index(){
return "author.getName()"+authorSettings.getName()+" author.getAge() "+authorSettings.getAge();
}
public static void main(String[] args) {
SpringApplication.run(ZXYApplication.class, args);
}
}
(4)运行http://localhost:8080
author.getName()zxy11 author.getAge() 20