springboot ConfigurationProperties 注解配置参数

1,327 阅读1分钟

在编写项目代码时,我们要求更灵活的配置,更好的模块化整合。在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值

1. 在yml或properties中配置参数

##线程池配置
audit-analysis:
  thread-pool:
    core-pool-size: 30
    maximum-pool-size: 60
    keep-alive-time: 1000
    blocking-queue-size: 1000

2. 配置Properties类

注解@Component,Properties类纳入Spring Bean, 后期可注入到使用之处

@Component
@Validated
@ConfigurationProperties(prefix = "audit-analysis.thread-pool", ignoreUnknownFields = true)
public class ThreadPoolProperties {

    /**
     * 核心线程数
     */
    @NotNull
    private int corePoolSize;
    /**
     * 最大线程数
     */
    @NotNull
    private int maximumPoolSize;
    @NotNull
    private int keepAliveTime;
    @NotNull
    private int blockingQueueSize;

}

3.配置类使用

 private static class ThreadPoolExecutorHolder {
        private static ThreadPoolProperties threadPoolProperties =
                SpringApplicationContext.getBean(ThreadPoolProperties.class);

        private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(
                threadPoolProperties.getCorePoolSize(),
                threadPoolProperties.getMaximumPoolSize(),
                threadPoolProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(threadPoolProperties.getBlockingQueueSize()),
                new ThreadFactoryBuilder().setNameFormat("audit-thread-%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }