1.@ConfigurationProperties
1.使用@ConfigurationProperties为第三方bean绑定属性
@Bean//将实例对象注入到IOC容器中 @ConfigurationProperties(prefix = "datasource") public DruidDataSource dataSource(){ DruidDataSource dataSource = new DruidDataSource(); return dataSource; }datasource: driverClassName: com.mysql.jdbc.Driver456
2.@EnableConfigurationProperties
@EnableConfigurationProperties可以将@ConfigurationProperties对应的类加入Spring容器中
@EnableConfigurationProperties和@Component不能同时使用,如果同时使用会报有两个bean的错误
2.宽松绑定
1.@ConfigurationProperties属于宽松绑定
注意:宽松绑定不支持注解@Value引用单个属性方式
3.常用的计量单位
1.SpringBoot支持JDK8提供的时间与空间计量单位
4.数据校验
开启数据校验有助于系统安全性,J2EE规范中JSR303规范定义了一组有关数据校验相关的API
开启数据校验的步骤
1.添加JSR3.3规范坐标与Hibernate校验框架对应的坐标
<!--导入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开启校验功能
@Validated public class ServerConfig {
3.设置校验规则
//这个类会加载对应的属性,要受到spring的管控 /*@Component*/ //将属性yml文件中的信息加载这个类中 @ConfigurationProperties(prefix = "servers") //1.开启bean属性校验 @Validated public class ServerConfig { private String ipAddress; //2.设置bean属性校验值 @Max(value = 8888,message = "最大不能超过8888") @Min(value = 20,message = "最小不能小于200") private int port; private long timeout; @DurationUnit(ChronoUnit.HOURS)//设置时间单位 private Duration serveTimeOut; @DataSizeUnit(DataUnit.KILOBYTES)//设置数据存储单位 private DataSize dataSize; public ServerConfig() { } public ServerConfig(String ipAddress, int port, long timeout, Duration serveTimeOut) { this.ipAddress = ipAddress; this.port = port; this.timeout = timeout; this.serveTimeOut = serveTimeOut; } public DataSize getDataSize() { return dataSize; } public void setDataSize(DataSize dataSize) { this.dataSize = dataSize; } public Duration getServeTimeOut() { return serveTimeOut; } public void setServeTimeOut(Duration serveTimeOut) { this.serveTimeOut = serveTimeOut; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public long getTimeout() { return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } @Override public String toString() { return "ServerConfig{" + "ipAddress='" + ipAddress + '\'' + ", port=" + port + ", timeout=" + timeout + ", serveTimeOut=" + serveTimeOut + ", dataSize=" + dataSize + '}'; } }
5.yaml的语法格式
注意:yaml文件中对于数字的定义支持进制书写格式,如需使用字符串请使用引导明确标注