Reputation: 2242
I want to config 3 thread pool parameter,So I write the vale in the config.How to inject them in spring bean.Here is my yml file config.
spring:
threadpool:
pool1:
corePoolSize: 1
maxPoolSize: 10
pool2:
corePoolSize: 2
maxPoolSize: 20
pool3:
corePoolSize: 3
maxPoolSize: 30
Here is the bean.Is that right?
@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 { }
}
In the other bean,I try to get each pool parameter like poolConfig.Pool1,but I can not do that,How to fix it?
@Autowired
PoolConfig poolConfig;
Upvotes: 0
Views: 395
Reputation: 394
I think you can do it like this,
@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, ...
}
}
I personally recommend to use list. Your yml should look like,
spring:
threadpool:
- poolName: pool1
corePoolSize: 1
maxPoolSize: 10
- corePoolSize: 2
poolName: pool2
maxPoolSize: 20
- poolName: pool3
corePoolSize: 3
maxPoolSize: 30
and your PoolConfig class should be like,
@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, ...
}
}
See also the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding and https://www.baeldung.com/spring-boot-yaml-list
Upvotes: 1