一 点睛
使用@Value注入每个配置,在实际使用上会显得很麻烦,因为我们的配置通常会有成百上千,如果通过这种方式,需要@Value注入很多次。
Spring Boot还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全配置。
二 实战
1 新建一个Spring Boot项目。
2 在src/main/resources路径下新建配置文件teacher.properties
teacher.name=cakin24
teacher.age=36
3 编写类型安全的Bean
package com.wisely.ch6_2_3.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
//加载properties文件内的配置,通过prefix属性指定properties的配置前缀
//通过locations指定配置文件的位置
@ConfigurationProperties(prefix = "teacher",locations = {"classpath:teacher.properties"})
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;
}
}
4 编写主类
package com.wisely.ch6_2_3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wisely.ch6_2_3.config.AuthorSettings;
@RestController
@SpringBootApplication
public class Ch623Application {
@Autowired
private AuthorSettings authorSettings; //可以用@Autowired直接注入该配置
@RequestMapping("/")
public String index(){
return "author name is "+ authorSettings.getName()+" and author age is "+authorSettings.getAge();
}
public static void main(String[] args) {
SpringApplication.run(Ch623Application.class, args);
}
}
三 运行结果