2017-04-04 26 views
0

上午實現自定義所有的Spring數據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。

+2

怎麼樣把一個春天的註釋,比如' TenantAwareRepositoryImpl上的@ Component'或'@ Repository'? –

回答

0

我想自定義行爲添加到所有存儲庫:

THS的問題是,TenantAwareRepositoryImpl類應該implementTenantAwareRepository如下所示:

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

您的回答假設我正試圖將自定義行爲添加到單個存儲庫。那麼我試圖將自定義行爲添加到所有的存儲庫,並遵循文檔中提到的步驟。定製存儲庫實現工作,並能夠設置一個斷點和調試。但問題是我們無法在自定義存儲庫實現中注入Spring bean。 – FFL

+0

您可以嘗試將'@ Component'添加爲TenantAwareRepositoryCustomImpl的類級別註釋嗎? – developer

+0

我明白了,看看上面的答案 – developer