Search code examples
javaspringspring-restcontroller

Implementation method not being called from Rest Controller using Spring


I'm trying to call an implementation method from my controller class. I've annotated the interface with @Component and Autowired this interface in my controller. But, its throwing me 404 exception.

On another way, I created a simple DAO and annotated with @Component, this is working from my controller.

My question is I want to follow by calling an interface method, which inturn will call the DAO.

Here is my flow.

@RestController
public class PurchaseController {

/*@Autowired
private DpDAO dpDAO;*/  ----> This is working
@Autowired
private PurchaseService purchaseService; --> This is not working

@GetMapping("/purchase/{partyId}/{dealId}")
public String createPurchase(@PathVariable("partyId") String partyId, @PathVariable("transactionId") String transactionId) {
    return purchaseService.createPurchase(partyId, transactionId); --> This is not working
    //return dpDAO.createPurchase(partyId, transactionId); --> This is working
}
}

My interface

@Component
public interface PurchaseService {
    public String createPurchase(String partyId, String transactionId);
}

DpDAO class

@Component
public class DpDAO  {

public String createPurchase(String partyId, String dealId) {
    // Able to get logs here
    return null;
}

}

Cannot we annotate the interfaces? Any ideas would be greatly appreciated.


Solution

  • I suspect the issue is that PurchaseService is an interface, while DpDAO is a class. That is, you have an instance of the latter but not of the former.

    If that's true, then Spring cannot find a bean to inject. So you'll need some way of creating an instance of PurchaseService to be injected.

    You could create an instance thus:

    @Component
    class PurchaseServiceImpl implements PurchaseService
    {
         // Fill in
    }
    

    Or you have a factory method on one of your initialiser classes. Something like:

    @Bean
    public PurchaseService createService()
    {
         return new PurchaseServiceImpl();
    }