
声明:
- 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();
}
文件目录下具体使用
生产环境中,小型项目可能需要指定具体目录下的自定义配置文件,避免反复的打包部署,实操如下:
1.yaml配置自定义配置文件在服务器的路径
config:
location: /data/rosetta/config/textclf-config.properties
2.创建配置文件对应的实体类
@ConfigurationProperties(prefix = "example")
@PropertySource(value = "file:${config.location}")
@Component
public class WeightScope { private String name;
private String scope; set ... get
}
注意:区别于项目路径下的 classpath ,服务器具体节点的配置使用 file
3.具体调度
// 注入自定义配置类
@Autowired
private WeightScope weightScope; // 直接使用即可
logger.info("request--weightScope:"+weightScope.getScope());
知识储备:
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; }