Spring boot says it requires a certain bean

Viewed 319

This is the userService class that requires a bean of type com.example.repository.userRepository that could not be found

package com.example.services;

import javax.transaction.Transactional;

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

import com.example.modal.User;
import com.example.repository.userRepository;


@Service
@Transactional
public class UserService {

 @Autowired
 private userRepository userRepository;


 public UserService() {
    super();
}

public UserService(userRepository userRepository)
 {
     this.userRepository = userRepository;
 }

 public void saveMyuser(User user) {
     userRepository.save(user);
 }
}

The error message reads :

Consider defining a bean of type 'com.example.repository.userRepository' in your configuration.

This is the repository:

package com.example.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;


import com.example.modal.User;


public interface userRepository extends CrudRepository<User,Integer> {

}

this is the application class

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
public class TutorialProjectApplication {

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

}

3 Answers

Seems like userRepository interface is outside of spring-boot default scanning i.e. package of that repository interface is not same or sub-package of the class annotated with @SpringBootApplication. If so, you need to add @EnableJpaRepositories("com.example.repository") on your main class.

Update: After looking at your updated post, you need to add @EnableJpaRepositories("com.example.repository") to TutorialProjectApplication class

Always keep the @SpringBootApplication main class outer package so that it will automatically scan all the subpackages.

In your case you have main class in package com.example.demo; but the repository in package com.example.repository; which are different packages.so spring boot is not able to find the repositories.

So you have to make spring boot aware of the repositories location.

So now you have 2 solutions.

1.Either put repository class in subpackges of Main class package.

2.Or use @EnableJpaRepositories("com.example.repository") in main class.

In your repository you need to annotate the class

@Repository
public interface userRepository extends CrudRepository<User,Integer> {

}
Related