为什么在这个例子中使用了一个 Bean - 它看起来像是毫无意义的间接寻址?
Why a Bean is being used in this example - it appears like pointless indirection?
在如何设置异步服务的this example中,由于某种原因,RestTemplate 的设置非常迂回。
为什么异步例程本身不能声明一个新的 RestTemplate?
@Service
public 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);
}
//...
Why can't the asynchronous routine itself just declare a new
RestTemplate?
这里显然没有价值。
RestTemplate
如果没有在其他地方重复使用,可以简单地使用 new
运算符创建。
如果我们想在其他地方重用它,将它声明为 @Bean
是有意义的。
它确实在另一个需要的 bean 中提供了单例 injectable/reusable。
但通常我们不会像这段代码那样在 @Service
class 中这样做,而是在更全局的配置 class 中这样做。
在如何设置异步服务的this example中,由于某种原因,RestTemplate 的设置非常迂回。
为什么异步例程本身不能声明一个新的 RestTemplate?
@Service
public 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);
}
//...
Why can't the asynchronous routine itself just declare a new RestTemplate?
这里显然没有价值。
RestTemplate
如果没有在其他地方重复使用,可以简单地使用 new
运算符创建。
如果我们想在其他地方重用它,将它声明为 @Bean
是有意义的。
它确实在另一个需要的 bean 中提供了单例 injectable/reusable。
但通常我们不会像这段代码那样在 @Service
class 中这样做,而是在更全局的配置 class 中这样做。