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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM