@Configuration 用于创建创建新 bean 的类(通过使用 @Bean 注释其方法):
@Configuration
public class CustomConfiguration {
@Bean
public SomeClass someClass() {
return new SomeClass();
}
}
@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
}
现在我们可以创建一个 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();
}
}
这样做的好处是它比在ZookeeperProperties 的每个字段中添加@Value 更简洁。相反,您在 @Bean 方法上提供单个注释,Spring 会自动将它找到的具有匹配前缀的任何外部配置绑定到该类的字段。
它还允许我的班级的不同用户(即创建ZookeeperProperties bean 类型的任何人)使用他们自己的前缀来配置班级。