java - Class的Spring clear属性值有@Async方法
问题描述
我尝试在 Spring Boot 2.4.4 中使用 @Async
process1
我在类 AsyncService 中实现了一个异步方法。
AsyncService 的 Bean 在AsyncConfig
类中定义(范围原型),随机数是传递给构造函数的参数。
AsyncService
问题是,当我向类的构造函数注入两个实例时AsyncTest
,它们没有为属性设置值AsyncService.prop111
//@Service
public class AsyncService {
static final Logger logger = LoggerFactory.getLogger(AsyncService.class);
public final long prop111;
public AsyncService(long prop111) { this.prop111 = prop111; }
@Async
public CompletableFuture<String> process1(int param) throws InterruptedException {
logger.info("start process1: [{} {}]", Thread.currentThread().getId(), Thread.currentThread().getName());
Thread.sleep(3000L);
return CompletableFuture.completedFuture("process1 result");
}
}
@Service
@EnableAsync
public class AsyncConfig {
@Bean("serviceAsync")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public AsyncService get() {
return new AsyncService(ThreadLocalRandom.current().nextInt(100,200));
}
}
@Service
public class AsyncTest {
static final Logger logger = LoggerFactory.getLogger(AsyncTest.class);
static AsyncService asyncService11;
static AsyncService asyncService22;
public AsyncTest(AsyncService asyncService11,
AsyncService asyncService22) {
AsyncTest.asyncService11 = asyncService11;
AsyncTest.asyncService22 = asyncService22;
// it can not set prop1111
logger.info("prop111 {} {} ", asyncService11.prop111, asyncService22.prop111);
}
public static void testAsync() throws InterruptedException, ExecutionException {
// it print 0, 0. prop111 is not init.
logger.info("prop111 {} {} ", asyncService11.prop111, asyncService22.prop111);
List<CompletableFuture<String>> futureList = IntStream.range(0, 10)
.mapToObj(asyncService11::process1)
.collect(Collectors.toList());
CompletableFuture<String>[] futureArray = futureList.toArray(new CompletableFuture[0]);
futureList.toArray(futureArray);
// waiting for all thread complete
CompletableFuture.allOf(futureArray).join();
logger.info("Elapsed time: ");
}
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
AsyncTest.testAsync();
};
}
}
解决方案
推荐阅读
- html - 如何将我自己的表单插入到搜索栏准备好的 Codepen 模板中
- c# - NPOI 是否可以在一个单元格中使用两种不同颜色的文本?
- java - 等价于 c# BitArray.CopyTo 的 java BitSet
- node.js - 如何使用 sinon 存根模块方法的回调?
- java - 使用带有服务令牌的 Java 应用程序从 hashcorp 保险库获取秘密
- debugging - Elixir Wallaby 在混合测试中崩溃
- python - python的tarfile函数addfile是否有可能不将所有数据读入内存?
- reactjs - 域映射(允许我的用户拥有自定义域)
- javascript - Detox 找不到已指定 testId 的自定义组件
- reactjs - 如何将函数的结果传输到另一个组件?