@EnableConfigurationProperties 注解

作用

  • @EnableConfigurationProperties的作用是开启@ConfigurationProperties。
  • @ConfigurationProperties的作用是将配置文件转换成类对象,便于修改或者获取值。

配置文件

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

local.host=127.0.0.1
local.port=8080

ConfigurationProperties

创建一个类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 + "]";
    }

}

EnableConfigurationProperties

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

package com.example.demo;
import org.springframework.boot.SpringApplication;
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();
    }
}

输出

ComponentProperties [host=127.0.0.1, port=8080]

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×