声明:
- spring boot 1.5 以后,ConfigurationProperties取消locations属性,因此采用PropertySource注解配合使用
- 根据Spring Boot2.0官方文档,PropertySource注解,只支持properties文件,因此排除 YAML配置
- 针对二,可考虑新建配置类,自行搜索,不再此次讨论范围
具体使用:
1.根目录下新建自定义配置文件夹与properties配置文件
example.name=tom example.wife=jerry example.age=25 example.dream=top
2.创建配置文件对应的实体类
@ConfigurationProperties(prefix = "example") @PropertySource(value = "classpath:config/config-test.properties") @Component public class ExampleConfig { private String name; private String wife; private String age; private String dream; get ... set }
3.注入,直接调用
// 自定义配置文件对应配置类 注入 @Autowired private ExampleConfig exampleConfig; @RequestMapping(value = "/hello",method = RequestMethod.GET) @ResponseBody public String sayHello(){ return exampleConfig.getName() + "的老婆是" + exampleConfig.getWife() + ", 年龄" + exampleConfig.getAge() + "岁,梦想是" + exampleConfig.getDream(); }
知识储备:
ConfigurationProperties源码:
@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ConfigurationProperties { /** * The name prefix of the properties that are valid to bind to this object. Synonym * for {@link #prefix()}. * @return the name prefix of the properties to bind */ @AliasFor("prefix") String value() default ""; /** * The name prefix of the properties that are valid to bind to this object. Synonym * for {@link #value()}. * @return the name prefix of the properties to bind */ @AliasFor("value") String prefix() default ""; boolean ignoreInvalidFields() default false; boolean ignoreUnknownFields() default true; }
原文地址:https://www.cnblogs.com/nyatom/p/9072902.html
时间: 2024-11-05 19:39:49