从spring boot文档中,@ConfigurationProperties将
从带@ConfigurationProperties注释的项目生成您自己的配置元数据文件
我尝试在配置类上单独使用use @Configuration和@ConfigurationProperties。
@Component
//@Configuration
@ConfigurationProperties
@EnableSpringDataWebSupport
@EnableAsync
public class AppConfig {
...
}
Run Code Online (Sandbox Code Playgroud)
我没有发现任何明显的差异。
@ConfigurationProperties或的用途是@Configuration什么?
@Configuration用于创建类并创建新bean(通过使用注释其方法@Bean):
@Configuration
public class CustomConfiguration {
@Bean
public SomeClass someClass() {
return new SomeClass();
}
}
Run Code Online (Sandbox Code Playgroud)
@ConfigurationProperties将外部配置绑定到其注释的类的字段中。通常将它与一种@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
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以创建一个类型的bean,ZookeeperProperties并使用外部配置自动填充它:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,与添加@Value到的每个字段相比,它不那么冗长ZookeeperProperties。相反,您在@Bean方法上提供了一个注释,Spring会自动将它找到的所有带有匹配前缀的外部配置绑定到该类的字段。
它还允许我班的不同用户(即创建Bean类型的任何人ZookeeperProperties)使用自己的前缀来配置班。
ConfigurationProperties 的用例用于外部化配置。
@Configuration
@Bean方法,并且可以由 Spring 容器处理以在运行时生成 bean 定义和这些 bean 的服务请求。@ConfigrationProperties
--如果您想要绑定和验证某些外部属性(例如来自 .properties 文件),则将其添加到类定义或类@Bean中的方法中。@Configuration
请参阅屏幕截图来@Value区分@ConfigurationProperties。
| 归档时间: |
|
| 查看次数: |
2881 次 |
| 最近记录: |