4、@ConfigurationProperties和@EnableConfigurationProperties配合使用

来源:互联网 发布:淘宝虚假发货如何辨别 编辑:程序博客网 时间:2024/05/20 21:44

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

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

local.host=127.0.0.1local.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*/@EnableConfigurationPropertiespublic 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]
原创粉丝点击