Question

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.

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top