Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
388 views
Welcome To Ask or Share your Answers For Others

1 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 "";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...