Spring MVC-静态上下文中自动连接的存储库NullPointerException [英] Spring MVC - Autowired Repository NullPointerException in static context
问题描述
在我的模型中,我有一个名为UserRepository
的存储库.另外,我有一个UserFacade
,它基本上将用户添加到存储库中,并且可以由Controller访问.存储库是立面中的@Autowired
.当我想添加一个新用户时,我会为存储库得到一个nullPointerException.
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.
我的spring-servlet.xml
包含必需的
<jpa:repositories base-package="project.user.repositories" />
而存储库是包含UserRepository.java
的文件夹.它扩展了CrudRepository:
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
是包含存储库的对象:
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
}
}
在我的controller
中,我有一个类似的方法:
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";
}
当我使用Android Studio时,导入应该不会成为问题.我想念什么?
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.
推荐答案
Spring不会自动关联static
字段.这就是为什么userRepo
字段为null
的原因.一种方法是使UserFacade
本身成为bean,然后可以使userRepo
为非静态字段.我希望这样. UserFacade
不应真正是实用程序类,因为它正在与存储库bean交互.将其制成一个bean会更有意义.
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.
另一种选择是提供设置器,并在其上使用@Autowired
:
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.
这篇关于Spring MVC-静态上下文中自动连接的存储库NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!