优化2. 上面的只能实现一个线程池对象,但是实际项目中并不只是这一个线程池对象,所以接下来我们需要进行优化!
创建一个DtpUtil 将来用来存放创建的多个线程池对象
```package com.laoyang.dtp;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
- @author:Kevin
- @create: 2023-10-24 22:29
- @Description: 线程安全的ConcurrentHashMap
*/
public class DtpUtil {
// public static ConcurrentHashMap map = new ConcurrentHashMap<>();
public static HashMap map = new HashMap<>();
public static void set(String name,DtpExecutor dtpExecutor){
map.put(name,dtpExecutor);
}
public static DtpExecutor get(String name) {
return map.get(name);
}
}
实现手动注册bean对象
```package com.laoyang.dtp;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
/**
* @author:Kevin
* @create: 2023-10-24 21:57
* @Description: 注册配置文件bean
*/
public class DtpImportBeanDefinationRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
//传入配置文件对象
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
//注册bean,读取用户配置的dtp后面定义的线程池列表,然后转换为DtpProperties对象
DtpProperties dtpProperties = new DtpProperties();
Binder binder = Binder.get(environment);
ResolvableType type = ResolvableType.forClass(DtpProperties.class);
Bindable<?> target = Bindable.of(type).withExistingValue(dtpProperties);
binder.bind("dtp",target);
//遍历配置,拿到所有的线程池列表
for (DtpProperties.DtpExecutorProperties executorProperties : dtpProperties.getDtpExecutors()) {
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
beanDefinition.setBeanClass(DtpExecutor.class);
//往这个DtpExecutor的有参函数中传入两个值
beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(executorProperties.getCorePoolSize());
beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(executorProperties.getMaximumPoolSize());
registry.registerBeanDefinition(executorProperties.getName(),beanDefinition);
}
}
//
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
同时不要忘了在核心配置类注入这个配置