Home > Enterprise >  Spring boot MVC - Unable to Autowire Repository in the service class
Spring boot MVC - Unable to Autowire Repository in the service class

Time:03-20

I have service class defined with @Autowired annotation for the corresponding repository

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StoreService {

    @Autowired
    private StoreRepository repository;

The repository interface is defined as extends from JpaReepository

import org.springframework.data.jpa.repository.JpaRepository;

public interface StoreRepository extends JpaRepository<Store, String> {
}

And the application Autowires the Service Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
public class StoreController {

    @Autowired
    private StoreService service;

Upon Running I get following error

***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in com.mypackage.service.StoreService required a bean of type 'com.mypackage.respository.StoreRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.mypackage.respository.StoreRepository' in your configuration.

CodePudding user response:

I think you should annotate your repository with @Repository, then it will be enabled automatically by Spring Framework.

@Repository
public interface StoreRepository extends JpaRepository<Store, String> {
}

CodePudding user response:

Just add the @Repository annotation to the StoreRepostiry and it should work.

Here are the most used annotations that Spring recognizes and can be used for auto wiring without the need to explicitly declaring it as a bean: @Service, @Repository and @Component

  • Related