springboot项目获取配置文件的三种方法

一、@Value注解

配置文件

param:
  url: www/

Java文件

@Configuration
public class Param {

    @Value("${param.url}")
    private String url;

}

二、@ConfigurationProperties注解

还可以配合 @PropertySource(value = “paramconfig.properties”)注解从指定的文件中获取值,方便统一管理。

注意:如果application.yml中也有这个参数,则优先加载主配置文件的值

@Data
@Configuration
@ConfigurationProperties(prefix = "param")
//可以指定文件来源 项目中用到的值都放在一个文件里
// @PropertySource(value = "paramconfig.properties")
public  class ParamConfig {

    public String url;

}

三、@EnableConfigurationProperties()注解

可获得指定Java类中的信息

package com.jerry.original.config;

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

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wjy
 * @date 2022/9/19
 */
@Configuration
// @ConfigurationProperties(prefix="thread")
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadPoolProperties entity){
        return new ThreadPoolExecutor(
                entity.getCorePoolSize(), //核心线程数
                entity.getMaxPoolSize(),//最大线程数
                entity.getKeepAliveTime(),//空闲线程的存活时间
                TimeUnit.SECONDS,//空闲线程存活时间的单位
                new LinkedBlockingDeque<>(10000),//阻塞队列
                new ThreadPoolExecutor.AbortPolicy()//拒绝策略
        );
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐