1. 程式人生 > >Spring Boot2.0自定義配置文件使用

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

default 創建配置文件 efault 知識 因此 @property pin bsp object

聲明:

  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(); }

知識儲備:

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;

}

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