在這個如何設置異步服務的示例中,出于某種原因,RestTemplate 以非常迂回的方式設置。為什么異步例程本身不能聲明一個新的 RestTemplate?@Servicepublic class AsyncService { private static Logger log = LoggerFactory.getLogger(AsyncService.class); @Autowired private RestTemplate restTemplate; @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Async("asyncExecutor") public CompletableFuture<EmployeeNames> getEmployeeName() throws InterruptedException { log.info("getEmployeeName starts"); EmployeeNames employeeNameData = restTemplate.getForObject("http://localhost:8080/name", EmployeeNames.class); log.info("employeeNameData, {}", employeeNameData); Thread.sleep(1000L); //Intentional delay log.info("employeeNameData completed"); return CompletableFuture.completedFuture(employeeNameData); } //...
1 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
為什么異步例程本身不能聲明一個新的 RestTemplate?
顯然這里沒有價值。如果沒有在其他地方重用,RestTemplate
可以簡單地用操作符創建。如果我們想在其他地方重用 它,聲明它是有意義的。 它確實在另一個需要它的 bean 中提供了單例可注入/可重用。 但通常我們不會像這段代碼那樣在一個類中這樣做,而是在一個更全局的配置類中這樣做。 new
@Bean
@Service
添加回答
舉報
0/150
提交
取消