@ConfigurationProperties(prefix = GatewayProperties.PREFIX)
示例
假设你有以下的配置属性在application.yml文件中:
gateway:
host: localhost
port: 8080
endpoints:
- /api
- /admin
你想将这些配置绑定到一个Java Bean上。首先,定义一个带有@ConfigurationProperties注解的Bean:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "gateway")
public class GatewayProperties {
public static final String PREFIX = "gateway";
private String host;
private int port;
private List<String> endpoints;
// getters and setters
}
在这个例子中,@ConfigurationProperties(prefix = "gateway")告诉Spring Boot,这个Bean的属性应该从配置文件中以gateway为前缀的属性中获取值。因此,host、port和endpoints字段将分别被绑定到gateway.host、gateway.port和gateway.endpoints配置属性的值。
注意事项
通过使用@ConfigurationProperties,可以将配置属性的管理集中化,提高代码的可读性和维护性。
- 使用@ConfigurationProperties时,通常需要在类路径上添加spring-boot-configuration-processor依赖,以生成元数据信息,这有助于IDE提供自动完成和文档提示。
- Bean需要定义setter方法,因为@ConfigurationProperties是通过调用这些方法来绑定属性值的。
- 你可以使用@Validated注解来添加验证逻辑,确保配置属性满足特定条件(例如,非空、格式正确等)。
- @ConfigurationProperties可以与@PropertySource注解结合使用,指定自定义的配置文件。