Spring Boot @RepositoryEventHandler 未调用 [英] Spring Boot @RepositoryEventHandler not invoked
问题描述
我已经设置了一个 @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.
推荐答案
可能会发生一些事情.
你的 repo 没有用 @RestResource
注释,但我猜这只是一个疏忽.
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.
如果你想捕获任何 repo 事件,不管入口点,那么你想使用 AbstractRepositoryEventListener
If you want to capture any repo event, regardless of entry point, then you want to use a AbstractRepositoryEventListener
Spring 数据休息事件文档 涵盖了这一点.另请参阅在 Spring Boot 中侦听存储库事件.
The Spring Data Rest Events documentation covers this. Also see listening for repository events in spring boot.
这篇关于Spring Boot @RepositoryEventHandler 未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!