@Autowired在SimpleJpaRepository扩展中不起作用

时间:2016-10-05 08:27:44

标签: spring-data spring-data-jpa

尝试覆盖SimpleJpaRepository时,通过@Autowired添加其他bean无效。在这种情况下如何注入豆类?这是一个实现:

public class BaseDAO<T, ID extends Serializable>
             extends SimpleJpaRepository<T, ID>
             implements IDAO<T, ID> {
  @Autowired
  private SomeBean someBean; // NULL!
}

2 个答案:

答案 0 :(得分:3)

BaseDAO的实例本身不是Spring管理的bean,因此通过@Autowired进行自动装配将无法实现开箱即用。因此,需要将依赖关系注入BaseDAO个实例。

  

第1步:在某处提供ApplicationContext个春天

@Component
class SpringContext implements ApplicationContextAware {
  private static ApplicationContext CONTEXT;

  public void setApplicationContext(final ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  public static ApplicationContext getContext() { return CONTEXT; }
}

在创建存储库时,需要自动装配自定义存储库实现的依赖项。

  

第2步:扩展SimpleJpaRepository

class BaseDAO<T, ID extends Serializable>
      extends SimpleJpaRepository<T, ID> {
  @Autowired
  private Dependency dependency;
}
  

第3步:通过JpaRepositoryFactoryBean

自动挂载相关性
class ExtendedJPARepositoryFactoryBean<R extends JpaRepository<T, ID>, T, ID extends Serializable>
      extends JpaRepositoryFactoryBean<R, T, ID> {
  private static class ExtendedJPARepositoryFactory<T, ID extends Serializable> extends JpaRepositoryFactory {
    public ExtendedJPARepositoryFactory(final EntityManager entityManager) {
      super(entityManager);
    }

    protected Class<?> getRepositoryBaseClass(final RepositoryMetadata metadata) {
      return isQueryDslExecutor(metadata.getRepositoryInterface())
             ? QueryDSLJPARepository.class
             // Let your implementation be used instead of SimpleJpaRepository.
             : BaseDAO.class;
    }

    protected <T, ID extends Serializable> SimpleJpaRepository<?, ?> getTargetRepository(
        RepositoryInformation information, EntityManager entityManager) {
      // Let the base class create the repository.
      final SimpleJpaRepository<?, ?> repository = super.getTargetRepository(information, entityManager);

      // Autowire dependencies, as needed.
      SpringContext.getContext()
                   .getAutowireCapableBeanFactory()
                   .autowireBean(repository);

      // Return the fully set up repository.
      return repository;
    }
  }

  protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
    return new ExtendedJPARepositoryFactory(entityManager);
  }
}
  

步骤4a :配置Spring Data JPA以使用工厂bean(XML配置)

<jpa:repositories base-package="org.example.jpa"
                  factory-class="org.example.jpa.ExtendedJPARepositoryFactoryBean"/>
  

步骤4b :配置Spring Data JPA以使用工厂bean(Java配置)

@EnableJpaRepositories(repositoryFactoryBeanClass = ExtendedJPARepositoryFactoryBean.class)

答案 1 :(得分:-2)

为了让Spring知道它需要在你的DAO中注入一些内容,你需要用@Component注释它。

您可以在此处详细了解:http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-spring-beans-and-dependency-injection.html