0

i just started my basic spring project and encountered some weird problem with beans and autowiring.

Field repository in app.user.UserModelImpl required a bean of type 'app.user.UserRepository' that could not be found.

UserModel.java

public interface UserModel {

    List<User> findAll();
}

UserModelImpl.java

@Service
public class UserModelImpl implements UserModel {
    @Autowired
    private UserRepository repository;

    @Override
    public List<User> findAll() {
        List<User> users = (List<User>) repository.findAll();
        return users;
    }
}

UserController.java

@RestController
public class UserController {
    @Autowired
    UserModel userModel;

    @GetMapping("/")
    public List findUsers(Model model)
    {
        System.out.println("HERE");
        List<User> users = userModel.findAll();

       return users;
    }
}

UserRepository.java

@Component
public interface UserRepository extends JpaRepository<User, Long> {
}

Application.java

@SpringBootApplication(scanBasePackages={"app.user"})
public class Application {

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

All these files are in the same package called user. I'm totally new in this topic so I'm sorry if this is something really basic or trivial.

  • Every "class name" (e.g. `UserRepository`) exists in a *NAMESPACE* (i.e. a Java "package"). Q:What packages are "UserModel", "UserModelImpl" and "UserRepository" in? Q: Did you get a clean compile (before the runtime error)? See this link: [Field required a bean of type that could not be found error spring restful API](https://stackoverflow.com/a/43166993/421195) – paulsm4 Nov 24 '19 at 23:56
  • I have them all in one package named User, but reordering them into different packages does not help. Also any solutions proposed in this topic does not solve my issue – Wichura Nov 26 '19 at 19:43
  • The problem is very clear: you've got a class (UserModelImpl) that needs another class (UserRepository) .. but Spring can't find it. I don't know how much you've "left out" of the code you posted (it looks reasonably "complete" ... but it's obviously not *everything*). SUGGESTIONS: 1) Look [here](https://www.baeldung.com/spring-data-annotations), particularly the part about `@EnableMongoRepositories`. 2) Create an [MCVE] (with just your app root, simple model interface/impl and your repository) and post it here. PS: Do you really want your "model" to be a "Service"? – paulsm4 Nov 26 '19 at 21:21

0 Answers0