@Configuration和@configurationProperties之间的SpringBoot区别

时间:2018-10-30 20:04:54

标签: spring-boot

spring boot documentationclass CacheCatalogue() { val CachedDataFrames = mutable.ArrayBuffer[DataFrame]() def AddToCache(dataFrame:DataFrame) { dataFrame.cache CachedDataFrames += dataFrame } } val catalogue = new CacheCatalogue()

  

从带注释的项目生成您自己的配置元数据文件   @ConfigurationProperties

我尝试在配置类上分别使用@ConfigurationProperties@Configuration

@ConfigurationProperties

我没有发现任何明显的差异。

@Component //@Configuration @ConfigurationProperties @EnableSpringDataWebSupport @EnableAsync public class AppConfig { ... } @ConfigurationProperties的用途是什么?

2 个答案:

答案 0 :(得分:4)

@Configuration用于创建一个类,该类创建新的bean(通过使用@Bean注释其方法):

@Configuration
public class CustomConfiguration {

    @Bean
    public SomeClass someClass() {
        return new SomeClass();
    }
}

@ConfigurationProperties将外部配置绑定到其注释的类的字段中。通常将它与@Bean方法一起使用来创建一个新的bean,该bean封装了可以在外部控制的配置。

这是我们如何使用它的真实示例。考虑一个简单的POJO,其中包含与连接ZooKeeper相关的一些值:

public class ZookeeperProperties
{
    private String connectUrl;

    private int sessionTimeoutMillis = (int) TimeUnit.SECONDS.toMillis(5);

    private int connectTimeoutMillis = (int) TimeUnit.SECONDS.toMillis(15);

    private int retryMillis = (int) TimeUnit.SECONDS.toMillis(5);

    private int maxRetries = Integer.MAX_VALUE;

    // getters and setters for the private fields
}

现在,我们可以创建ZookeeperProperties类型的bean,并使用外部配置自动填充它:

@Configuration
public class ZooKeeperConfiguration {

    @ConfigurationProperties(prefix = "zookeeper")
    @Bean
    public ZookeeperProperties zookeeperProperties() {

        // Now the object we create below will have its fields populated
        // with any external config that starts with "zookeeper" and
        // whose suffix matches a field name in the class.
        //
        // For example, we can set zookeeper.retryMillis=10000 in our
        // config files, environment, etc. to set the corresponding field
        return new ZookeeperProperties();
    }
}

这样做的好处是,它比在@Value的每个字段中添加ZookeeperProperties更为冗长。相反,您在@Bean方法上提供了一个注释,Spring会自动将找到的带有匹配前缀的任何外部配置绑定到该类的字段。

它还允许班级的不同用户(即创建ZookeeperProperties bean类型的任何人)使用自己的前缀来配置班级。

答案 1 :(得分:1)

ConfigurationProperties的用例用于外部化配置。

@配置

  • 表示一个类声明了一个或多个@Bean方法,并且可以由Spring容器处理以在运行时为这些bean生成bean定义和服务请求。

@ConfigrationProperties

-如果要绑定和验证某些外部属性(例如,来自.properties文件),则添加到@Configuration类的类定义或@Bean方法中。

请参见屏幕截图,以区分@Value和@ConfigurationProperties。

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

ConfigrationProperties use case