我有自己的自定义Spring Data公共存储库,以便为所有Spring Data存储库提供通用行为。我只需要在创建存储库时修改EntityManager。但由于bean是通过new运算符创建的,因此无法将Spring bean注入JpaRepositoryFactoryBean。
public class BasicJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {
@Autowired
private SomeService service; // - it does not work
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
// do some logic here
service.doSmth();
return new CommonRepositoryFactory<>(em);
}
private static class CommonRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
private final EntityManager em;
public CommonRepositoryFactory(EntityManager em) {
super(em);
this.em = em;
}
@SuppressWarnings("unchecked")
protected Object getTargetRepository(RepositoryMetadata metadata) {
JpaEntityInformation entityInformation = getEntityInformation(metadata.getDomainType());
return new CommonRepositoryImpl(entityInformation, em);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return CommonRepositoryImpl.class;
}
}
}
答案 0 :(得分:0)
在该类中实现一个setter或从中扩展一个setter。