首页 > 其他 > 详细

@ConfigurationProperties的用法实践

时间:2021-06-24 10:33:04      阅读:10      评论:0      收藏:0      [点我收藏+]

作用

在SpringBoot中,当需要获取到配置文件数据时,除了可以用Spring自带的@Value注解外,SpringBoot提供了一种更加方便的方式:@ConfigurationProperties。只要在bean上添加上这个注解,指定好配置文件的前缀,那么对应的配置文件数据就会自动填充到bean中。

示例

下面使用@ConfigurationProperties配置线程池的参数。

第一步 引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

该依赖需要重启项目才会生效。

第二步 新建一个类用于存放需要配置的参数名

package com.atbgpi.mall.product.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

//此处添加注解,指定配置字段的前缀
@ConfigurationProperties(prefix = "mall.thread")
@Component
@Data
public class MyThreadPollConfigProperties {
    private Integer coreSize;
    private Integer maxSize;
    private Integer keepAliveTime;
}

第三步 在application.properties中配置参数

mall.thread.core-size=100
mall.thread.max-size=500
mall.thread.keep-alive-time=10

第四步 使用此配置

package com.atbgpi.mall.product.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class MyThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(MyThreadPollConfigProperties config) {
        return new ThreadPoolExecutor(config.getCoreSize(),
                config.getMaxSize(),
                config.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}

@ConfigurationProperties的用法实践

原文:https://www.cnblogs.com/bGpi/p/14924992.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!