美文网首页
Spring Boot相关注解

Spring Boot相关注解

作者: 零一_fb4d | 来源:发表于2018-03-11 14:15 被阅读0次

@ConfigurationProperties与@EnableConfigurationProperties

1、作用

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

2、使用

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

local.host=127.0.0.1
local.port=8080
  1. 创建一个类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 + "]";
    }

}
  1. 用@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注解。

  1. 输出结果如下:
ComponentProperties [host=127.0.0.1, port=8080]

总结:

①首先有一个配置文件application.properties
②在一个实体类上使用@ConfigurationProperties注解可以把properties文件转化为bean,
然后使用@Component注解把该bean注入到IOC容器中
③启动类上:用@ComponentScan扫描到该类,
用@EnableConfigurationProperties注解使@ConfigurationProperties生效,并从IOC容器中获取bean。

相关文章

网友评论

      本文标题:Spring Boot相关注解

      本文链接:https://www.haomeiwen.com/subject/zqgifftx.html