Spring Boot2.0自定义配置文件使用

声明:

  1. spring boot 1.5 以后,ConfigurationProperties取消locations属性,因此采用PropertySource注解配合使用
  2. 根据Spring Boot2.0官方文档,PropertySource注解,只支持properties文件,因此排除 YAML配置
  3. 针对二,可考虑新建配置类,自行搜索,不再此次讨论范围

 项目路径下具体使用:

  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;

}

转载于:https://www.cnblogs.com/nyatom/p/9072902.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值