在自定义所有存储库中注入bean

时间:2017-04-04 10:27:49

标签: java spring-boot spring-data-jpa spring-security-oauth2

实现自定义的所有Spring Data Jpa存储库,如

@NoRepositoryBean
public interface TenantAwareRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {

@Override
Page<T> findAll(Pageable pageable);
}

并像

一样实施
@Slf4j
public class TenantAwareRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements UserAwareRepository<T, ID>{

    @Autowired
    private ResourceServerTokenServices defaultTokenServices;

    private final EntityManager entityManager;

    public TenantAwareRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);

        // Keep the EntityManager around to used from the newly introduced methods.
        this.entityManager = entityManager;
    }

    public Page<T> findAll(Pageable pageable){
        OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        log.info("Token = {}", details.getTokenValue());
        return null;
    }

}

不幸的是defaultTokenServices没有被注入,而是null。如何在自定义所有存储库实现中注入spring bean。

1 个答案:

答案 0 :(得分:0)

  

我正在尝试向所有存储库添加自定义行为:

问题是TenantAwareRepositoryImpl班级implement TenantAwareRepository如下所示:

@Component
@Slf4j
public class TenantAwareRepositoryImpl<T, ID extends Serializable> 
   extends SimpleJpaRepository<T, ID> implements TenantAwareRepository<T, ID>{
    //add your code here
}