参考:@EnableConfigurationProperties 注解的含义与使用说明
SpringBoot获取application配置文件中参数的三种方式
方式一: @ConfigurationProperties(prefix = “”) 注解
bean的属性配置加载
正确的bean的属性配置加载
@Data
@Component
@ConfigurationProperties(prefix = "yyzx.properties")
public class AnnotationDesc {
}
错误A bean的属性配置加载
@Data
@ConfigurationProperties(prefix = "yyzx.properties")
public class AnnotationDesc {
// 该书写方式,属性值注入失败
}
纠正: 错误A bean的属性配置加载
@Data
@ConfigurationProperties(prefix = "yyzx.properties")
public class AnnotationDesc {
// 该书写方式,属性值注入成功
}
@Slf4j
@Configuration
@EnableConfigurationProperties({
AnnotationDesc.class,
YyzxProperties2.class
})
public class SpringBootPlusConfig {
}
结果
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。
@EnableConfigurationProperties 是把指定类的属性又注入了一次。
@EnableConfigurationProperties标注的类,不能和@Component同时使用
方法二、通过@Value()注解也可以给bean对象属性添加数值
通过@Value(“${servers.ipAddress}”)
bean属性校验
https://blog.csdn.net/m0_46690280/article/details/122844963
1、导入依赖
<!--JSR303规范校验工具-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<!--使用hibernate框架提供的校验器做实现类-->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
2、开启对当前bean的属性注入校验
@Data
@Component
@ConfigurationProperties(prefix = "servers")
//开启对当前bean的属性注入校验
@Validated
public class ServerConfig {
private String ipAddress;
@Max(value = 8888,message = "最大值不能超过8888")
@Min(value = 202,message = "最小值不能小于202")
private int port;
private long timeout;
}