1,properties 文件内容映射到类对象 (属性), 如 Resource 目录下的 1.properties 文件已配置前缀为 com.imooc.people 相关的信息, 然后:
pom 添加依赖: springboot-configuration-processor
People 类对象上方添加注解:
- @Configuration
- @PropertySource(value="classpath:1.properties") // 指定从哪个 properties 读取内容
- @ConfigurationProperties(prefix="com.imooc.people") // 指定读取的前缀
- public class{
- private String name;
- private String age;
...name,age 的 getter/setter...
}
然后直接在 controller 中 @Autowired 可直接获取到有属性值的 People 对象
2,YAML 文件内容映射到类对象 (属性),YAML 格式不支持 @PropertySource 注解导入, 一般用 @Value. 如 Resource 目录下的 1.properties 文件已配置前缀为 com.imooc.people 相关的信息, 然后:
- @Configuration // 或者 @Component
- public class{
- @Value("${com.imooc.people.name}")
- private String name;
- @Value("${com.imooc.people.age:#{null}}") //age 取不到对应配置值时, 采用默认值 null 赋值
- private String age;
...name,age 的 getter/setter...
}
来源: http://www.bubuko.com/infodetail-3350523.html