参考:@EnableConfigurationProperties 注解的含义与使用说明
SpringBoot获取application配置文件中参数的三种方式

方式一: @ConfigurationProperties(prefix = “”) 注解

bean的属性配置加载
正确的bean的属性配置加载

  1. @Data
  2. @Component
  3. @ConfigurationProperties(prefix = "yyzx.properties")
  4. public class AnnotationDesc {
  5. }

错误A bean的属性配置加载

  1. @Data
  2. @ConfigurationProperties(prefix = "yyzx.properties")
  3. public class AnnotationDesc {
  4. // 该书写方式,属性值注入失败
  5. }

纠正: 错误A bean的属性配置加载

  1. @Data
  2. @ConfigurationProperties(prefix = "yyzx.properties")
  3. public class AnnotationDesc {
  4. // 该书写方式,属性值注入成功
  5. }
  6. @Slf4j
  7. @Configuration
  8. @EnableConfigurationProperties({
  9. AnnotationDesc.class,
  10. YyzxProperties2.class
  11. })
  12. public class SpringBootPlusConfig {
  13. }

结果
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。
@EnableConfigurationProperties 是把指定类的属性又注入了一次。
@EnableConfigurationProperties标注的类,不能和@Component同时使用

方法二、通过@Value()注解也可以给bean对象属性添加数值

通过@Value(“${servers.ipAddress}”)

bean属性校验

https://blog.csdn.net/m0_46690280/article/details/122844963

1、导入依赖

  1. <!--JSR303规范校验工具-->
  2. <dependency>
  3. <groupId>javax.validation</groupId>
  4. <artifactId>validation-api</artifactId>
  5. </dependency>
  6. <!--使用hibernate框架提供的校验器做实现类-->
  7. <dependency>
  8. <groupId>org.hibernate.validator</groupId>
  9. <artifactId>hibernate-validator</artifactId>
  10. </dependency>

2、开启对当前bean的属性注入校验

  1. @Data
  2. @Component
  3. @ConfigurationProperties(prefix = "servers")
  4. //开启对当前bean的属性注入校验
  5. @Validated
  6. public class ServerConfig {
  7. private String ipAddress;
  8. @Max(value = 8888,message = "最大值不能超过8888")
  9. @Min(value = 202,message = "最小值不能小于202")
  10. private int port;
  11. private long timeout;
  12. }