Spring Boot第四弹:Spring Boot之@Value和@ConfigurationProperties
来源:互联网 发布:犀牛软件版本分析 编辑:程序博客网 时间:2024/05/29 02:38
Spring Boot之@Value和@ConfigurationProperties
小弟刚接触spring boot不久,仅想通过写网志的形式来加深记忆和方便以后查阅。如内容有不正确之处,还望各位大佬海量汪涵,并给小弟指出,共同进步。
1.@ConfigurationProperties校验
每当使用Spring注解@Validated时,Spring Boot都会尝试校验该类。可以直接在配置类上使用JSR-303约束注解,只需保证类路径中JSR-303的实现,然后在属性上添加约束注解:
@ConfigurationProperties(“book”)@Validated public class BookProperties{ @NotNull private String bookName; //setter和getter}
1.1校验嵌套属性的值
为了校验嵌套属性的值,必须使用@Valid注解在相关属性上,以触发其校验。如:
@ConfigurationProperties(prefix=“book”)@Validated public class BookProperties{ @NotNull private String bookName; @Valid private final Security security = newSecurity(); //setter和getter public static class security{ @NotNull public String price; //setter和getter }}
2. @ConfigurationProperties
通常希望把配置文件的信息,读取并自动封装成实体类,在这时就可以使用@ConfigurationProperties。
如:application.yml
spring: application: name: ng_knowmanage #-----------redis config------------------- redis: cluster: expiration: 30 max-redirects: 3 nodes: - 172.17.200.4:6380 - 172.17.200.4:6381 - 172.17.200.4:6382
Demo.class:
@Component@ConfigurationProperties(prefix=“spring.redis.cluster”) public class Demo{ List<String> nodes; Integer expiration; Integer maxRedirects //setter和getter}
3.@Value
@Value注解用来读取配置文件中属性。
如:application.yml
aliyun: ossurl: xxx
Demo.class:
@Componentpublicclass Demo{ @Value(“${aliyun.ossurl}”) String ossurl; //setter和getter}
可将需要的单个属性配置,加载到java代码中。
4.@Value和@ConfigurationProperties
@Value是一个核心容器功能,不提供与类型安全配置属性相同的功能。
简单的个人理解:
@ConfigurationProperties是将application配置文件的某类名下所有的属性值,自动封装到实体类中。
@Value是将application配置文件中,所需要的某个属性值,封装到java代码中以供使用。
阅读全文
0 0
- Spring Boot第四弹:Spring Boot之@Value和@ConfigurationProperties
- spring boot 通过@Value,@ConfigurationProperties获取配置
- 学习Spring boot 注解 @Value @Component @ConfigurationProperties
- spring boot 使用@ConfigurationProperties
- Spring boot @ConfigurationProperties
- spring-boot @ConfigurationProperties脑洞真大
- spring boot 使用@ConfigurationProperties
- spring boot 使用@ConfigurationProperties
- Using @ConfigurationProperties in Spring Boot
- Spring boot源码分析-ConfigurationProperties
- spring-boot配置(一):@Configuration,@ConfigurationProperties和application.yml
- Spring boot 通过@ConfigurationProperties和@PropertySource读取自定义配置文件信息
- 在Spring Boot中使用 @ConfigurationProperties 注解
- spring boot:使用@ConfigurationProperties注解加载配置文件
- 在spring-boot中使用@ConfigurationProperties
- spring boot @ConfigurationProperties @EnableConfigurationProperties 配置注解使用
- Spring Boot 使用@ConfigurationProperties注解获取配置文件中的值
- spring boot @Value取值
- c++常用头文件
- java socket-3--多客户端与服务器的交互
- 多个session共享数据如何实现
- MacOS 开发
- LeetCode题解 week2(2)
- Spring Boot第四弹:Spring Boot之@Value和@ConfigurationProperties
- Day12 Servlet
- 文章标题
- 用C语言建立链表并进行基础操作
- Unity前期学习的内容,以及一些可能遇到的问题
- 图像语义分割:从头开始训练deeplab v2系列之四【nyu v2数据集】
- 46muduo库使用示例(五)
- 第三周项目二 建设“顺序表”算法库
- centos启动_某个开机启动的服务有问题导致不能启动