Properties 类 和 @ConfigurationProperties 注解 ( yaml 时间格式)

Spring的 @Conditional 系列注解和 Spring Starter

一、Properties类

  1. new:Properties类相当于一个Hashtable (不能使用父类的 put / get方法)
  2. load:使用时load方法加载一个 inputstream
// jdk方式读取资源流
InputStream resourceAsStream = AClass.class.getResourceAsStream("/application.properties");
// spring 方式读取资源
Resource classPathResource = new ClassPathResource("/mybatis-config.xml");
InputStream inputStream = classPathResource.getInputStream();
  1. size:判断读取的内容是否为空
  2. getProperty:传入key的字符串获取
  3. setProperty:传入key和value,等同于在HashTable中插值
  4. store:传入outputstream和comments字符串,将所有内容保存到硬盘。其中comments会出现在首行。其他行不会出现注释,无法单独注释

二、@ConfigurationProperties

  1. prefix="spring.redis" 前缀定义了哪些外部属性将绑定到类的字段上,也就是配置文件中的前缀后面的字段应和类一一对应(prefix并不是全限定名,是通过把类的每个成员变量挨个赋值,类似于@Value)
  2. 对应的对象必须有:
    1. 公共的 Setter 方法 (读取)
    2. 公共的 Getter (告知 spring-configuration-metadata.json 文件 properties 属性, 这样才不显示波浪号)
  3. 可以作用于类和方法上,类上时需要结合 @EnableConfigurationProperties 注解使用, 或加上 @Component 注解
@Configuration
public class DataSourceConfig {    
    @Bean(name = "redidsUtil")
    public RedisUtil redidsUtil() {
        return new RedisUtil();
    }
}

---

@ConfigurationProperties(prefix = "util.redis")
public class RedisUtil {...}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(DefaultAuthenticationEventPublisher.class)
@EnableConfigurationProperties(SecurityProperties.class)
@Import({ SpringBootWebSecurityConfiguration.class, WebSecurityEnablerConfiguration.class, SecurityDataConfiguration.class, ErrorPageSecurityFilterConfiguration.class })
public class SecurityAutoConfiguration {...}

---

@ConfigurationProperties(prefix = "spring.security")
public class SecurityProperties {
	private final User user = new User();
	
	public static class User {
		private String name = "user";
	}
}
  1. 当将该注解作用于方法上时,需要加上 @Bean 注解且所属 Class 需要有 @Configuration 注解
@Configuration
public class DruidDataSourceConfig {
    /**
     * 对象填充并交给Bean管理
     * @return
     */
    @ConfigurationProperties(prefix = "util.redis")
    @Bean(name = "redisUtil")
    public RedisUtil redisUtil() {
        return new RedisUtil();
    }
}
public class RedisUtil {
...

Spring 宽松绑定规则 (relaxed binding)

threadPool可以匹配的值:thread-pool、threadpool、threadPool、thread_pool、THREAD_POOL

  1. 属性配置错误类型时,Spring Boot 应用启动会失败,我们可以设置 ignoreInvalidFields 属性为 true 来避免
  2. 当配置文件中某个属性没有绑定到 @ConfigurationProperties 类时,Spring Boot 会默认忽略。将 ignoreUnknownFields 属性设置为 false 可触发通知。
  3. Spring Boot 内置 Duration类 解析 durations (持续时间) 如time=3s 。不写单位,默认按照ms毫秒来设置。可通过注解@DurationUnit(ChronographUnit.SECONDS) 来指定对象默认为秒.
  4. DataSize类 解析文件大小,默认单位是 byte (字节),可以通过 @DataSizeUnit 指定单位.
  5. 如果我们不自定义转化器提供给 Spring 则必须以 yyyy/MM/dd 格式赋值, 这是 Spring 默认提供的日期转换器格式 (以 yyyy-MM-dd 或者 yyyyMMdd 都会报错)
@Setter
@ConfigurationProperties(prefix="author")
public class TestProperties {

	private String name;
	private Integer age;
	private String phone;
	private Boolean isboy;
	private Float ppt;
	private Date birthday;
	
}


@Configuration(proxyBeanMethods = false)@EnableConfigurationProperties(TestProperties.class)
public class TestAutoConfiguration {
  @AutoWired
  private TestProperties tst;
  
  ...
}

配置文件 (yaml)

author:
	birthday: 2222/2/2 2:2:2

三、@PropertySource

@PropertySource 注解用于指定资源文件读取的位置, 能读取 properties / xml 配置文件

@PropertySource(value = "classpath:code-message.properties", encoding = "UTF-8")
class XXConfiguration {

PropertySourceFactory 的默认实现 DefaultPropertySourceFactory 是解析不了 yaml 文件的, 可配合自定义 PropertySourceFactory 实现解析 YAML 文件. (可引用第三方jar 包进行解析 org.yaml:snakeyaml)

    // 创建资源文件解析器,spring4.3之前需要
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

四、yaml 提示

如果想让自己写的配置类, 能在yaml 配置文件中显示, 可以加入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>2.6.3</version>
    <scope>provided</scope>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值