一、Springboot1.x @ConfigurationProperties的用法

Springboot1.x中通过@ConfigurationProperties注解来实现对bean的自定义属性的注入,需要在配置文件中配置相应的属性,然后通过@ConfigurationProperties注解将配置文件中的属性注入到bean中,具体代码如下:

@ConfigurationProperties(prefix = "my")
public class MyProperties {
    private String name;
    private int age;
    //getter、setter省略
}

其中,@ConfigurationProperties注解的prefix属性值指定配置文件中的属性的前缀,然后在配置文件中配置相应的属性,如:

my.name=张三
my.age=18

二、Springboot2.x @ConfigurationProperties的用法

Springboot2.x中也可以通过@ConfigurationProperties注解来实现对bean的自定义属性的注入,与Springboot1.x的用法类似,但Springboot2.x在此基础上增加了一个refresh属性,可以对bean的自定义属性进行刷新,具体代码如下:

@ConfigurationProperties(prefix = "my",refresh = true)
public class MyProperties {
    private String name;
    private int age;
    //getter、setter省略
}

在Springboot2.x中,通过@ConfigurationProperties注解的refresh属性设置为true,可以实现对bean的自定义属性的实时刷新,即在配置文件中修改属性后,bean中的属性值也会实时刷新,而不需要重启应用。

三、Springboot1.x和2.x @ConfigurationProperties的区别

从上面的代码可以看出,Springboot1.x和2.x中通过@ConfigurationProperties注解实现对bean的自定义属性的注入的用法基本一致,但Springboot2.x新增了一个refresh属性,可以实现对bean的自定义属性的实时刷新,这也是Springboot1.x和2.x @ConfigurationProperties用法的区别。