欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-27 20:25:24
...
  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;
}

[email protected]

//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();
       // ...........
   }   
相关标签: springboot