springboot的@EnableConfigurationProperties注解

阅读数:507 评论数:0

跳转到新版页面

分类

python/Java

正文

一、概述

@EnableConfigurationProperties注解的作用是:让使用了@ConfigurationProperties注解的类生效,并且将该类注入到IOC容器中,交由IOC容器进行管理。

如果一个类只配置了@ConfigurationProperties注解,而没有使用@Component注解将该类加入到IOC容器中,那么它就不能完成xxx.properties配置文件和Java Bean的数据绑定。

二、使用

1、配置参数

application.properties

myapp.mail.enabled=true
myapp.mail.default-subject=This is a Test-

我们可以使用@Value注解或者使用Spring Environment bean访问这些属性,也可以使用@ConfigurationProperties来获取这些属性

@Data
@ConfigurationProperties(prefix="myqpp.mail")
public class MailModuleProperties{
    private Boolean enabled = Boolean.TRUE;
    private String defaultSubject;
}

(1)前缀定义了哪些外部属性将绑定到类的字段上。

(2)类本身可以package或private

(3)类的字段必须有公共的setter方法

2、Spring宽松绑定规则

以下变体都将绑定到hostName属性上:

mail.hostName=localhost
mail.hostname=localhost
mail.host_name=localhost
mail.host-name=localhost
mail.HOST_NAME=localhost

3、激活配置类的方法

方式一:@Component+@ConfigurationProperties,让Component Scan扫描到。

方式二:@Configuration+@Bean

方式三:@EnableConfigurationProperties




相关推荐

一、概述 springboot中有两种方式使用kafka时,直接使用kafka-client连接kafka服务;另一种是使用spring-kafka框架来连接kafka。 1、版本兼容 使用时要注意版

当然可以自己写redis的工具类,或者使用第三方开源jar包或代码,这里使用spring boot的集成类。 一、pom依赖 <dependency> <gro

websocket协议基于tcp的网络协议,它实现浏览器与器全双工通信。 spring boot2 +websocket 1、添加依赖 <pre clas

背景: 之前用spring boot+mybatis+oracle,现在要改成spring boot_mybatis+postgresql。 为了想让一套代码即可

共同点 都是用来表示Spring某个类是否可以接收HTTP请求。 不同点 @Controller标识一个spring类是Spring MVC c

系统异常捕获 参见:spring boot 2 全局异常处理 @ControllerAdvice(annotations = {RestController.class}) public class

从SSH(Structs/Spring/Hibernate)到SSM(SpringMVC/Spring/MyBatis),到现在一个S(Spring)就够的年代,可见Spring越来越重要了。<

@ConditionalOnMissingBean只能在@Bean注解的方法上使用。 可以给该注解传入参数例如@ConditionOnMissingBean(name = "exa

2.4版本之前 在之前,我们在yaml配置文件中,使用spring.profiles来定义不同环境的标识,比如下面这样: <pre class="language-ma

在SpringBoot框架中,我们使用最多的是Tomcat,这是SpringBoot默认的容器技术,而且是内嵌式的Tomcat。   同时,SpringBoot也支持Undertow容器,Undert