当前位置: 首页 > news >正文

SpringBoot复习:(22)ConfigurationProperties和@PropertySource配合使用及JSR303校验

一、配置类

package cn.edu.tju.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "your")
@PropertySource("classpath:data/01.properties")
public class YourConfig {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}

二、data子目录下的01.properties

your.age=32
your.name=Chopin

三、controller中注入配置类:

package cn.edu.tju.controller;import cn.edu.tju.config.YourConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class TestController {@Autowiredprivate YourConfig yourConfig;@RequestMapping("/prop")public String getProp(){return yourConfig.getName() + " " + yourConfig.getAge();}
}

注意:
如果application.properties中也有your.age和your.name的配置,它会覆盖@PropertySource注解指定的属性文件中的配置,比如如下application.properties:

server.port=9032
spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx/test
spring.datasource.username=root
spring.datasource.password=My
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
your.age=23
your.name=tju

还可以在@ConfigurationProperties中使用JSR303校验。
1)加依赖

org.springframework.boot
spring-boot-starter-validation

2)在@ConfigurationProperties修饰的类上加@Validated注解,在属性上加校验注解:
在这里插入图片描述

http://www.lryc.cn/news/114880.html

相关文章:

  • Spring IoC (控制反转)
  • 安卓下模拟渲染EGLImageKHR
  • Spring MVC 框架学习总结
  • 2、简单上手+el挂载点+v-xx(v-text、v-html、v-on、v-show、v-if、v-bind、v-for)
  • C++初阶语法——命名空间
  • Axwing.878 线性同余方程
  • 【Pytorch+torchvision】MNIST手写数字识别
  • spring boot 集成rocketmq
  • redis Hash类型命令
  • P1194 买礼物(最小生成树)(内附封面)
  • oracle基础语法和备份恢复
  • 【MATLAB第66期】#源码分享 | 基于MATLAB的PAWN全局敏感性分析模型(有条件参数和无条件参数)
  • vue2过渡vue3技术差异点指南
  • 两个多选框(select)之间值的左右上下移动
  • 【设计模式】——模板模式
  • 工业机器视觉系统开发流程简介
  • 【Unity3D】Renderer Feature简介
  • 麻了!包含中科院TOP,共16本期刊被标记为“On Hold”状态!
  • 2.Flink应用
  • Matlab进阶绘图第25期—三维密度散点图
  • C++设计模式之桥接设计模式
  • 论文笔记:SUPERVISED CONTRASTIVE REGRESSION
  • Java 多线程并发 CAS 技术详解
  • 如何压缩高清PDF文件大小?将PDF文件压缩到最小的三个方法
  • 04 统计语言模型(n元语言模型)
  • Linux各目录详解
  • 【css】属性选择器分类
  • 备份容灾哪家好怎么样
  • 【前端实习生备战秋招】—HTML 和 CSS面试题总结(三)
  • Ansible Rsync 使用Ansible Rsync模块进行文件传输