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();
       // ...........
   }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值