未调用@RepositoryEventHandler

时间:2017-11-18 20:27:14

标签: spring spring-data-jpa

我为我的应用用户创建了一个简单的存储库:

@RepositoryRestResource(path = "users")
public interface AppUserRepository extends JpaRepository<AppUserModel, Long> {

    List<AppUserModel> findByUsername(@Param("username") String username);

}

但是,我需要在插入新用户之前处理密码加密。为此我实现了@RepositoryEventHandler

@RepositoryEventHandler(AppUserModel.class)
public class AppUserService {

    @HandleBeforeSave
    public void handleProfileSave(AppUserModel appUserModel) {
        System.out.println("Before save ..");
    }

    @HandleBeforeCreate
    public void register(AppUserModel appUserModel) {
        System.out.println("Before create ..");
    }

}

问题是这两个事件处理程序都没有被执行。结果AppUserModel被尝试保留但由于没有生成和设置盐(用于密码)而失败 - 这就是我可以告诉JpaRepository<AppUserModel, Long>到目前为止的工作方式。

{
"cause": {
    "cause": {
        "cause": null,
            "message": "ERROR: null value in column "password_salt" violates not-null constraint Detail: Failing row contains (26, 2017-11-18 21:21:47.534, 2017-11-18 21:21:47.534, f, asd, null, haha@gmx.at)."
        },
    "message": "could not execute statement"
    },
    "message": "could not execute statement; SQL [n/a]; constraint [password_salt]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}

2 个答案:

答案 0 :(得分:2)

在我看来,你只需要创建AppUserService bean。最简单的选择是使用@Component

对其进行注释
@Component
@RepositoryEventHandler(AppUserModel.class)
public class AppUserService {
    //...
}

答案 1 :(得分:0)

另一种方法是从另一个配置类中提供bean:

@Configuration
public class RepositoryConfiguration {

    @Bean
    AppUserEventHandler appUserService() {
        return new AppUserEventHandler();
    }
}

但是,我更喜欢@varren提供的解决方案。