[英]Spring MVC - Autowired Repository NullPointerException in static context
In my model I have a repository called UserRepository
.在我的模型中,我有一个名为UserRepository
的存储库。 Additionally I have a UserFacade
that basically adds the user to the repository and is accessed by the Controller.此外,我有一个UserFacade
,它基本上将用户添加到存储库并由控制器访问。 The repo is @Autowired
in the Facade.该 repo 是 Facade 中的@Autowired
。 When I want to add a new user I get a nullPointerException for the repository.当我想添加一个新用户时,我会收到存储库的 nullPointerException。
My spring-servlet.xml
contains the required我的spring-servlet.xml
包含所需的
<jpa:repositories base-package="project.user.repositories" />
while repositories is the folder containing the UserRepository.java
.而 repositories 是包含UserRepository.java
的文件夹。 It extends the CrudRepository:它扩展了 CrudRepository:
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
}
Facade.java
is the object containing repository: Facade.java
是包含存储库的对象:
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:从我的controller
我有一个方法,如:
@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.导入应该不会成为问题,因为我使用的是 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.注意:相关问题有很多很好的答案(比如这个),但每个都有自己的不同背景,对我没有帮助。
Spring doesn't autowire static
fields. Spring 不会自动装配static
字段。 That is why userRepo
field is null
.这就是userRepo
字段为null
。 One way is to make the UserFacade
a bean itself, and then you can make userRepo
a non-static field.一种方法是让UserFacade
本身UserFacade
一个 bean,然后你可以让userRepo
成为一个非静态字段。 I would prefer this way.我更喜欢这种方式。 UserFacade
shouldn't really be a utility class, since it is interacting with the repository bean. UserFacade
不应该是一个实用程序类,因为它与存储库 bean 进行交互。 It would make much more sense to make it a bean.把它做成豆子会更有意义。
Another option is to provide a setter, and use @Autowired
on that:另一种选择是提供一个setter,并在其上使用@Autowired
:
@Autowired
public void setUserRepo(UserRepository userRepo) {
UserFacade.userRepo = userRepo;
}
Or using it even on a parameterized constructor would work.或者甚至在参数化构造函数上使用它也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.