将 @HandleBeforeSave 方法添加到我的 @RepositoryEventHandler class 会从我的 REST API 中删除底层的 @Entiry

Adding a @HandleBeforeSave method to my @RepositoryEventHandler class removes the underlying @Entiry from my REST API

问题

我正在使用 spring 并且在这个过程中我添加了一个 @RepositoryEventHandler(User.class) 用于更新 (PUT) 当我去修改用户时。

我希望能够设置谁在对 User 进行编辑。

我创建了一个 @HandleBeforeCreate,它适用于 HTTP POST,但是一旦我添加了 @HandleBeforeSaveUser REST API 就是不再可用。我没有看到正在创建 stack trace

问题

关于创建 @HandleBeforeSave

我是否遗漏了什么

@RepositoryEventHandler

@Component
@RepositoryEventHandler(User.class)
public class SpringDataRestEventHandler {

    private final UserRepository userRepository;

    @Autowired
    public SpringDataRestEventHandler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @HandleBeforeCreate
    public void applyUserInformationUsingSecurityContext(User user) throws  {


        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        User manager = this.userRepository.findByUserName(name);

        if (!manager.hasRole("ROLE_MANAGER")) {
            throw new Exception("No manager found for user on applyUserInformationUsingSecurityContext.");
        }
        user.setManager(name);

    }

    @HandleBeforeSave
    public void applyManagerFromSecurityContext(User user)  {

        System.out.println("calling before save");
    }
}

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private SpringDataJpaUserDetailsService userDetailsService;

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
      .userDetailsService(this.userDetailsService)
        .passwordEncoder(MCBPasswordEncoder.PASSWORD_ENCODER);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers("/built/**", "/main.css").permitAll()
        .anyRequest().authenticated()
        .and()
      .formLogin()
        .defaultSuccessUrl("/", true)
        .permitAll()
        .and()
      .httpBasic()
        .and()
      .csrf().disable()  // TODO enable for production
      .logout()
              .invalidateHttpSession(true)
              .deleteCookies("JSESSIONID")
        .logoutSuccessUrl("/");
  }

}

最终问题实际上与我为 User @Entity 创建的 2 个存储库有关。我得到了奇怪的结果,其中 API 会出现(在一个回购中)并在另一个回购中消失。

我已经通过

解决了这个问题
  • 只使用一个存储库而不是两个扩展存储库 JPARepository
  • 从 PagingAndSortingRepository 复制并粘贴我需要的方法。
  • 相应地为特定方法添加了@PreAuthorize,而不是 class。这是最初的问题,因为当我想在 REST api.
  • 之外操作 repo 时,我把它分开了