您的当前位置:首页正文

SpringBoot读取application.yml/application.properties中的自定义配置

2024-11-30 来源:个人技术集锦

方式1:@ConfigurationProperties(prefix = “attachment.file”) + @EnableConfigurationProperties(AttachmentFileConfig.class)

① application.yml文件:

attachment:
  file:
    maxSize: 10
    types:
      jpeg: FFD8FF
      jpg: FFD8FF
      bmp: 424D
      png: 89504E47
      rtf: 7B5C727466
      txt: 75736167
      pdf: 255044462D312E
      doc: D0CF11E0
      docx: 504B030414000600080000002100

② 读取配置文件并封装成AttachmentFileConfig类:

@Data
@ConfigurationProperties(prefix = "attachment.file")
public class AttachmentFileConfig {
    private Double maxSize;
    private Map<String, String> types;
}

③ 使用AttachmentFileConfig类:

@EnableConfigurationProperties(AttachmentFileConfig.class)
@Configuration
public class AttachmentConfig {
    @Bean
    public AttachmentTypes attachmentTypes(AttachmentFileConfig attachmentFileConfig) {
        return new AttachmentTypes(attachmentFileConfig);
    }
}

方式2:@ConfigurationProperties(prefix = “gulimall.thread”) + @Component

① application.properties文件:

gulimall.thread.core-size=20
gulimall.thread.max-size=200
gulimall.thread.keep-alive-time=10

② 读取配置文件并封装成ThreadPoolConfigProperties类:

@ConfigurationProperties(prefix = "gulimall.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
    private Integer coreSize;
    private Integer maxSize;
    private Integer keepAliveTime;
}

③ 使用ThreadPoolConfigProperties类:

@Configuration
public class MyThreadConfig {
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties threadPoolConfigProperties){
        return new ThreadPoolExecutor(
                threadPoolConfigProperties.getCoreSize(),
                threadPoolConfigProperties.getMaxSize(),
                threadPoolConfigProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }
}
显示全文