尝试覆盖SimpleJpaRepository
时,通过@Autowired
添加其他bean无效。在这种情况下如何注入豆类?这是一个实现:
public class BaseDAO<T, ID extends Serializable>
extends SimpleJpaRepository<T, ID>
implements IDAO<T, ID> {
@Autowired
private SomeBean someBean; // NULL!
}
答案 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注释它。