首页 > 解决方案 > 如何从@Component 调用@Service 方法

问题描述

我有一个组件,我想从中调用服务方法。当我尝试打电话时,什么也没有发生。service 方法是调用 rest api 的 completablefuture 方法。这和它有什么关系吗?

我试过从不同的类调用它并且它有效。只有这个类是一个问题。

我从中调用它的类的片段:

@Component
@Scope("prototype")
public class Reader{  

///and other variable declarations used

@Autowired
private AsyncServices aService;


public void StartAsync() throws InterruptedException, IOException{

 Runnable task = new Runnable() {

@Override
public void run() {
   try {
    StartInventory();
 } catch (Exception ex) {
    System.out.print("start inventory thread could not start: 
 "+ex.getLocalizedMessage());}
            }
        };
        Runnable task2 = new Runnable() {

            @Override
            public void run() {
                try {
                    StartTCPClient();

                } catch (Exception ex) {
                    System.out.print("start tcpclient thread could not start: "+ex.getMessage());
                }
            }
        };

        tcpClientThread = new Thread(task2, "TCPClientThread");
       tcpClientThread.setDaemon(true);
        tcpClientThread.start();




      inventoryThread = new Thread(task, "InventoryThread");
        inventoryThread.setDaemon(true);
        inventoryThread.start();   

public void StartInventory() throws InterruptedException, ExecutionException, ParseException{

……

 //calling the method in @service class   
  aService.findVehicle(rfidtag);    

}

   code for service:
@Service
public class AsyncServices {   
private final RestTemplate appRestTemplate;

@Autowired
public AsyncServices(RestTemplateBuilder builder){
    this.appRestTemplate=builder.build();
}

@Async
 @Transactional
public CompletableFuture<BmwvehicleTest> findVehicle(String rfidtag) throws InterruptedException{
    log.info("trying to find a vehicle test by rfidtag"+ rfidtag);
     HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity <BmwvehicleTest> entity = new HttpEntity <BmwvehicleTest>(headers);
      BmwvehicleTest results=appRestTemplate.exchange("http://localhost/tag/"+rfidtag, HttpMethod.GET, entity, BmwvehicleTest.class).getBody();
    return CompletableFuture.completedFuture(results);


}

我希望能够从服务方法中获得结果,该方法从休息 api 中获得结果。

标签: javamultithreadingspring-bootresttemplate

解决方案


推荐阅读