更新:以下是使用Spring Boot 2.1.0
我有一个Spring数据存储库,我正在尝试为它提供一些自定义功能,遵循fragments example from the documentation。
因此,我向存储库添加了一个额外的接口:
public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
User findByFirstNameAndLastName(String firstName, String lastName);
}
使用此自定义接口:
interface UserExtraLogic {
void ensureHasAccess();
}
及其实现:
class UserExtraLogicImpl implements UserExtraLogic {
public void ensureHasAccess() {
}
}
问题是我希望能够在UserExtraLogicImpl
中使用我的存储库,这样我就可以重用像findByFirstNameAndLastName
这样的查询方法,而不必用EntityManager
自己编写它们。所以我试了一下:
class UserExrtaLogicImpl implements UserExtraLogic {
@Autowired
private UserRepository userRepository;
}
但是之后应用程序就不会启动了。我得到了一个NullPointerException,但我认为这只是Spring进入一个周期,试图解决这些依赖关系。
我想要做的事情是可能的吗?有没有其他方法可以做到这一点?
发布于 2019-05-31 14:00:50
您可以使用ObjectFactory<T>
(Spring概念)或Provider<T>
(标准java api)来延迟加载您的存储库。
class UserExrtaLogicImpl implements UserExtraLogic {
@Autowired
private ObjectFactory<UserRepository> userRepository;
public void soSomething() {
userRepository().getObject().findById(xxx);
}
}
发布于 2019-05-31 15:24:28
我有完全相同的代码模式,在最近的一个项目中遇到了同样的问题,我最终通过使用@Lazy
延迟初始化UserRepository
解决了这个问题:
class UserExrtaLogicImpl implements UserExtraLogic {
@Lazy
@Autowired
private UserRepository userRepository;
}
https://stackoverflow.com/questions/53322230
复制相似问题