Hearner
Hearner

Reputation: 2729

Field repository in my service required a bean that could not be found

Here is the error

Description:

Field userRepository in com.yaqari.service.UserService required a bean of type 'com.yaqari.repository.UserRepository' 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.yaqari.repository.UserRepository' in your configuration.

Here is my project structure :

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───yaqari
│   │           │   YaqariApplication.java
│   │           │   DataLoader.java
│   │           ├───controller
│   │           │       UserController.java
│   │           ├───model
│   │           │       User.java
│   │           ├───repository
│   │           │       UserRepository.java
│   │           └───service
│   │                   UserService.java
│   └───resources
│
└───test
    └───java

Controller is a @RestController :

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/users")
    public List<User> list() {
        return userService.findAll();
    }
}

Model is @Entity :

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long user_id;

    protected User() {
    }

}

Repository is a @Repository that extends CrudRepository

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}

Service is a @Service

@Service
public class UserService {

    @Autowired         // <- here seems to be the issue
    private UserRepository userRepository;

    public List<User> findAll() {
        Iterable<User> users = userRepository.findAll();
        ArrayList<User> userList = new ArrayList<>();
        users.forEach(e -> userList.add(e));

        return userList;
    }
}

Edit : I'm working with a sringboot application

@SpringBootApplication
public class YaqariApplication {

    public static void main(String[] args) {
        SpringApplication.run(YaqariApplication.class, args);
    }
}

Upvotes: 0

Views: 2409

Answers (1)

ABAZAR MOHITI
ABAZAR MOHITI

Reputation: 11

you should change pom.xml you need to

        <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>2.3.5.RELEASE</version>
         <relativePath /> <!-- lookup parent from repository -->
        </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

Upvotes: 1

Related Questions