有些时候,我们需要将一些第三方库中的配置类纳入到 spring 的管理,比如:配置线程池参数,怎么做比较优雅呢?
如果是 spring xml 的话,我们可能使用 spring 的属性注入来进行配置。
例如:
<bean id="myThreadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="2"></property>
<property name="threadNamePrefix" value="myPool-"></property>
</bean>
在 springboot 中,可以怎样优雅的进行配置呢?
SpringBoot 配置第三方 Bean 最佳实践
在 SpringBoot 中,可以使用 @Bean + @ConfigurationProperties 的方式,轻松实现 bean 属性的配置化:
@ConfigurationProperties(prefix = "my.executor")
@Bean(value = "myThreadPoolTaskExecutor", initMethod = "initialize")
public ThreadPoolTaskExecutor myThreadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
在 application.properties 中可以使用如下配置:
my.executor.corePoolSize=2
my.executor.threadNamePrefix=testxxx
又比如,我们在配置数据源时也可以使用如下配置:
@ConfigurationProperties(prefix = “spring.datasource.biz”)
@Bean
public DataSource bizDataSource() {
return DataSourceBuilder.create().build();
}
这样配置的话,我们就将 ThreadPoolTaskExecutor 类纳入到 spring 容器的管理了,同时,还可以通过配置项对 bean 中的属性进行配置。
利用 FactoryBean 做参数配置化技巧
有时一些第三方类的参数可能没有 getter/setter 方法,使用上面的方式就做不了参数配置化。
碰到这种情况,我们可以利用 FactoryBean 的特性,将参数配置放在 FactoryBean 中。
这样,spring 生成 bean 的时候会调用 getObject()
方法,就可以使用到我们配置的参数了。
定义 FactoryBean:
@Slf4j
@Data
public class ExecutorFactoryBean implements FactoryBean<ThreadPoolTaskExecutor> {
private int corePoolSize = 1;
private int maxPoolSize = Integer.MAX_VALUE;
private int keepAliveSeconds = 60;
private boolean allowCoreThreadTimeOut = false;
private int queueCapacity = Integer.MAX_VALUE;
private String threadNamePrefix;
@Override
public ThreadPoolTaskExecutor getObject() throws Exception {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setQueueCapacity(queueCapacity);
executor.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut);
executor.setThreadNamePrefix(threadNamePrefix);
log.info("use ExecutorProperties:{}", this);
executor.setRejectedExecutionHandler(new DiscardOldest());
executor.initialize();
return executor;
}
@Override
public Class<?> getObjectType() {
return ExecutorService.class;
}
}
通过 FactoryBean 来配置线程池:
@Slf4j
@Configuration
@EnableAsync(proxyTargetClass = true)
public class ExecutorsConfig {
public static final String BIZ_EXECUTOR = "bizExecutor";
/** 默认的异步执行器 */
@Primary
@ConfigurationProperties(prefix = "executor.normal")
@Bean
public ExecutorFactoryBean defaultExecutor() {
return new ExecutorFactoryBean();
}
@Bean(BIZ_EXECUTOR)
@ConfigurationProperties(prefix = "executor.biz")
public ExecutorFactoryBean bizExecutor() {
return new ExecutorFactoryBean();
}
}