I have the following controller.
The following line works just fine:
user = userRepository.selectUserByLogin(name);
It correctly returns the user.
@Controller
public class TestController {
@Autowired
private UserRepository userRepository;
@RequestMapping(method = RequestMethod.GET, value = "/testpage")
public String initTest() {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
User user = new User();
user = userRepository.selectUserByLogin(name);
return "";
}
}
Now I want to move that code to a getLoggedUser method of a "Utilities" class. This is how I did it.
Controller
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET, value = "/testpage")
public String initTest() {
Utilities utilities = new Utilities();
User user = new User();
user = utilities.getLoggedUser();
return "";
}
}
Utilities
public class Utilities {
@Autowired
private UserRepository userRepository;
public User getLoggedUser() {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
User user = new User();
user = userRepository.selectUserByLogin(name);
return user;
}
}
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.
question from:https://stackoverflow.com/questions/65598869/null-repository-even-with-autowired-implemented