Java 如何在Spring yml中注入具有相同属性的类?
我想配置3个线程池参数,所以我在配置中写入了vale。如何将它们注入Springbean。这是我的yml文件配置Java 如何在Spring yml中注入具有相同属性的类?,java,spring,spring-boot,Java,Spring,Spring Boot,我想配置3个线程池参数,所以我在配置中写入了vale。如何将它们注入Springbean。这是我的yml文件配置 spring: threadpool: pool1: corePoolSize: 1 maxPoolSize: 10 pool2: corePoolSize: 2 maxPoolSize: 20 pool3: corePoolSize: 3 maxPoolSize: 30 这是豆
spring:
threadpool:
pool1:
corePoolSize: 1
maxPoolSize: 10
pool2:
corePoolSize: 2
maxPoolSize: 20
pool3:
corePoolSize: 3
maxPoolSize: 30
这是豆子,对吗
@ConfigurationProperties(prefix = "spring.threadpool")
public class PoolConfig {
public class CommonPool {
public int getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
int corePoolSize;
int maxPoolSize;
}
public class Pool1 extends CommonPool { }
public class Pool2 extends CommonPool { }
public class Pool3 extends CommonPool { }
}
在另一个bean中,我尝试获取每个pool参数,如poolConfig.Pool1,但我不能这样做,如何修复它
@Autowired
PoolConfig poolConfig;
我想你可以这样做
@ConfigurationProperties
public class PoolConfig() {
private CommonPool pool1;
private CommonPool pool2;
private CommonPool pool3;
// getter, setter, ...
public static class CommonPool() {
private int corePoolSize;
private int maxPoolSize;
// getter, setter, ...
}
}
我个人建议使用列表。你的yml应该是这样的
spring:
threadpool:
- poolName: pool1
corePoolSize: 1
maxPoolSize: 10
- corePoolSize: 2
poolName: pool2
maxPoolSize: 20
- poolName: pool3
corePoolSize: 3
maxPoolSize: 30
您的PoolConfig类应该是
@ConfigurationProperties
public class PoolConfig() {
private List<CommonPool> pools;
// getter, setter, ...
public static class CommonPool() {
private String poolname;
private int corePoolSize;
private int maxPoolSize;
// getter, setter, ...
}
}
@ConfigurationProperties
公共类PoolConfig(){
私人名单池;
//getter,setter。。。
公共静态类CommonPool(){
私有字符串池名;
私有池大小;
私有int-maxPoolSize;
//getter,setter。。。
}
}
另见和