问题描述
我已经设置了@RepositoryEventHandler
,并且由于某些未知原因而没有调用它.
I've got a @RepositoryEventHandler
set up and it is not being invoked for some unknown reason.
@Component
@RepositoryEventHandler(User.class)
public class UserEventHandler {
@Autowired
private PasswordCrypto passwordCrypto;
@HandleBeforeSave
public void handleUserSave(User user) {
if (user.getPassword() != null && !"".equals(user.getPassword())) {
user.setPassword(passwordCrypto.encrypt(user.getPassword()));
}
}
@HandleBeforeCreate
public void handleUserCreate(User user) {
user.setPassword(passwordCrypto.encrypt(user.getPassword()));
}
}
存储库:
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findOneByUsername(String username);
}
我的主要班级:
@SpringBootApplication
@EntityScan("de.ihrig.feuerwehr.hydranet.model")
@EnableJpaRepositories
@ComponentScan({
"somepath",
"somepath including the UserEventHandler"
})
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
感谢您的提前帮助,我只是找不到错误.
Thanks for your help in advance, I just cannot find the error.
推荐答案
可能有几件事发生.
您的回购未带有/c1的批注,但我想那只是一个疏忽.
You're repo isn't annotated w/ @RestResource
, but I'm guess that was just an oversight.
我猜这些评论是正确的,您正在通过单元测试来测试它,而入口点没有通过REST API. handlers
仅捕获通过该向量传来的Repo事件.
I'm guessing the comments are correct and you're testing this through a unit test with an entry point that is not going through the REST API. The handlers
only capture Repo events that are coming through that vector.
如果您想捕获任何回购事件,无论进入点是什么,那么您都想使用AbstractRepositoryEventListener
If you want to capture any repo event, regardless of entry point, then you want to use a AbstractRepositoryEventListener
Spring Data Rest事件文档涵盖了这一点.另请参见在春季启动中监听存储库事件.
The Spring Data Rest Events documentation covers this. Also see listening for repository events in spring boot.
这篇关于Spring Boot @RepositoryEventHandler未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!