springboot @ConfigurationProperties和@EnableConfigurationProperties配合使用

转载自:https://blog.csdn.net/u010502101/article/details/78758330

@ConfigurationProperties注解主要用来把properties配置文件转化为bean来使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的。使用如下:

1、spring boot启动时默认是加载application.properties配置文件的,假设该配置文件中内容为:

local.host=127.0.0.1
local.port=8080
  •  

2、创建一个类ComponentProperties,把配置文件转化为bean来使用。@ConfigurationProperties注解可以把properties文件转化为bean,然后使用@Component注解把该bean注入到IOC容器中。

package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
/*prefix定义配置文件中属性*/
@ConfigurationProperties(prefix="local")
public class ComponentProperties {

    /*host和port属性必须保持与application.properties中的属性一致*/
    private String host;
    private String port;

    public void setHost(String host) {
        this.host = host;
    }
    public void setPort(String port) {
        this.port = port;
    }

    @Override
    public String toString() {
        return "ComponentProperties [host=" + host + ", port=" + port + "]";
    }

}

3、用@EnableConfigurationProperties注解使@ConfigurationProperties生效,并从IOC容器中获取bean。

package com.example.demo;
import org.springframework.boot.SpringApplication;
import 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

//@SpringBootApplication
@ComponentScan
/*@EnableConfigurationProperties注解是用来开启对@ConfigurationProperties注解配置Bean的支持。
也就是@EnableConfigurationProperties注解告诉Spring Boot 使能支持@ConfigurationProperties*/
@EnableConfigurationProperties
public class Springboot3Application {

    public static void main(String[] args) throws Exception {

        ConfigurableApplicationContext context = SpringApplication.run(Springboot3Application.class, args);
        /*@ConfigurationProperties注解和@EnableConfigurationProperties配合使用*/
        System.out.println(context.getBean(ComponentProperties.class));
        context.close();
    }
}

启动类如上,@ComponentScan注解默认扫描启动类所在的包,该包下的类如果注入到了IOC容器中,那么在该启动类就能获取注入的bean。然后用@EnableConfigurationProperties注解使@ConfigurationProperties注解生效。因此在该启动类中就可以获取刚才application.properties配置文件转化的bean了。另外,只使用@SpringBootApplication一个注解也是可以的,因为@SpringBootApplication注解中已经包含了@ComponentScan和@EnableConfigurationProperties注解。

4、输出结果如下:

ComponentProperties [host=127.0.0.1, port=8080]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值