我有一个线程池,并且在Spring中使用@value传递池大小的输入,其引用位于.properties文件中。如下所示:
@Value("${project.threadPoolSize}")
private static int threadPoolSize;
private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(threadPoolSize);
@PostConstruct
public void MasterProcessService() {
try {
LOGGER.debug("Entering processServices in MasterProcessThread ");
当我尝试使用注释值指定线程池大小时,它仅池化1个线程并执行睡眠操作,但以后不池化其他线程。
当我直接使用传递线程池大小时:
private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(11);
它将所有线程池化,并按定义从睡眠和运行状态开始。
有人可以帮助我在线程池大小中使用@Value而不是直接定义数字吗?
答案 0 :(得分:4)
这都是由于两个事实:
1-@Value
在静态字段上不起作用。如果要使用该值填充-请勿将其设为静态。
@Value("${project.threadPoolSize}")
private static int threadPoolSize;
2-在threadPool
填充值之前(如果它不是静态的),首先创建静态threadPoolSize
变量。
如果您需要通过@Value
将值设置为某个静态字段,则可以尝试如下操作:
private static ScheduledExecutorService threadPool;
@Value("${project.threadPoolSize}")
public void setThreadPool(Integer poolSize) {
threadPool = Executors.newScheduledThreadPool(poolSize);
}
将在启动时调用值注入,并将调用setThreadPool
方法,该方法将使用已定义的池大小初始化静态变量。
答案 1 :(得分:0)
Spring不允许将值注入静态变量。请改用java.lang.Integer
。