Skip to content
Advertisement

Null repository even with @Autowired implemented

I have the following controller.

The following line works just fine:

user = userRepository.selectUserByLogin(name);

It correctly returns the user.

JavaScript

Now I want to move that code to a getLoggedUser method of a “Utilities” class. This is how I did it.

Controller

JavaScript

Utilities

JavaScript

But when that is executed I’m getting the following error:

Cannot invoke “UserRepository.selectUserByLogin(String)” because “this.userRepository” is null.

Why is it null if it is with the @Autowired notation? Looks the same as in the original implementation that worked.

Advertisement

Answer

Spring is not going to be able to autowire your repository if you create an instance of Utilities class with new like: Utilities utilities = new Utilities();

In order to do so you will have to add @Component or @Service annotation to your Utilities class:

JavaScript

and then autowire it into your controller:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement