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.

@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.

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:

@Component
public class Utilities {

and then autowire it into your controller:

@Controller
public class TestController {

    @Autowired
    private Utilities utilities;

    @RequestMapping(method = RequestMethod.GET, value = "/testpage")
    public String initTest() {
        User user = new User();
        user = utilities.getLoggedUser();

        return "";
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement