Spring MVC - Autowired Repository NullPointerException in static context

autowired, java, spring, spring-mvc

Solution

Spring doesn't autowire `static` fields. That is why `userRepo` field is `null`. One way is to make the `UserFacade` a bean itself, and then you can make `userRepo` a non-static field. I would prefer this way. `UserFacade` shouldn't really be a utility class, since it is interacting with the repository bean. It would make much more sense to make it a bean.

Another option is to provide a setter, and use `@Autowired` on that:

@Autowired
public void setUserRepo(UserRepository userRepo) {
    UserFacade.userRepo = userRepo;
}

Or using it even on a parameterized constructor would work.

Problem

In my model I have a repository called `UserRepository`. Additionally I have a `UserFacade` that basically adds the user to the repository and is accessed by the Controller. The repo is `@Autowired` in the Facade. When I want to add a new user I get a nullPointerException for the repository. My `spring-servlet.xml` contains the required `<jpa:repositories base-package="project.user.repositories" />` while repositories is the folder containing the `UserRepository.java`. It extends the CrudRepository: ``` @Repository public interface UserRepository extends CrudRepository<User, Long> { User findByUsername(String username); } ``` `Facade.java` is the object containing repository: ``` public class UserFacade { @Autowired private static UserRepository userRepo; private static Logger logger = LoggerFactory.getLogger(UserFacade.class); public UserFacade(){} //Thought it might work if I add a constructor and call it? public static User findByUsername(String username) { logger.debug(username+userRepo); // prints SomeStringnull return userRepo.findByUsername(username); //NullPointerException } } ``` And from my `controller` I have a method like: ``` @RequestMapping(value = CONTEXT) public String test(){ User user = UserFacade.findByUsername("get"); //obviously user will be null if there is no such user return "success"; } ``` Imports will should not be a problem as I am using Android Studio. What did I miss? Note: There are many great answers to related questions (like this one), but each has it's own, different context and didn't help me.

Original source

Related problems