spring boot @ConfigurationProperties @EnableConfigurationProperties 配置注解使用

两者的区别是

 1、如果只使用ConfigurationProperties得花需要在对于类上面加上 @Component等注入Bean的注解,告诉sping-boot给纳入进去

2、如果不使用@Component的话这需要使用ConfigurationProperties(打ConfigurationProperties注解的类.class)来告诉spring-boot开启ConfigurationProperties注解

3、另外需要注意分级

  1. @ConfigurationProperties使用 
    application-dev.yml
my:
  servers:
    port: 8080
    threadPool:
      maxThreads: 100
      minThreads: 8
      idleTimeout: 6000
  • @ConfigurationProperties 使用
**
 * Created by jiyang on 16:10 2017/12/15
 */
@Controller
@RequestMapping("/tester")
@Api(value = "测试页面", description = "测试页面相关接口")
@ConfigurationProperties(prefix = "my.servers")
public class TestController {

    @Getter
    @Setter
    private int port;

    @Getter
    @Setter
    private Map<String,Object> threadPool;
}

2.@EnableConfigurationProperties

//file MyWebServerConfigurationProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "my.webserver")
public class MyWebServerConfigurationProperties {
    private int port;
    private ThreadPool threadPool;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public ThreadPool getThreadPool() {
        return threadPool;
    }

    public void setThreadPool(ThreadPool threadPool) {
        this.threadPool = threadPool;
    }

    public static class ThreadPool {
        private int maxThreads;
        private int minThreads;
        private int idleTimeout;

        public int getIdleTimeout() {
            return idleTimeout;
        }

        public void setIdleTimeout(int idleTimeout) {
            this.idleTimeout = idleTimeout;
        }

        public int getMaxThreads() {
            return maxThreads;
        }

        public void setMaxThreads(int maxThreads) {
            this.maxThreads = maxThreads;
        }

        public int getMinThreads() {
            return minThreads;
        }

        public void setMinThreads(int minThreads) {
            this.minThreads = minThreads;
        }
    }
}
// file: MyWebServerConfiguration.java
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@Configuration
@EnableConfigurationProperties(MyWebServerConfigurationProperties.class)
public class MyWebServerConfiguration {
    @Autowired
    private MyWebServerConfigurationProperties properties;
    /**
     *下面就可以引用MyWebServerConfigurationProperties类       里的配置了
    */
   public void setMyconfig() {
       String port = properties.getPort();
       // ...........
   }   

猜你喜欢

转载自blog.csdn.net/liyantianmin/article/details/81020689