BaseDAO
의 인스턴스는 스프링 관리 빈이 아니므로 @Autowired
을 통해 autowiring하면 즉시 사용할 수 없습니다. 따라서 종속성은 BaseDAO
인스턴스에 주입되어야합니다.
1 단계 : 되세요 곳
@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; }
}
이
이 저장소 생성시 사용자 정의 저장소 구현에 대한 종속성을 autowire하기 위해 필요합니다
ApplicationContext
사용할 수있는 봄.
단계 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);
}
}
통해 종속 0
4a 단계 : 구성 스프링 데이터 JPA이 공장 빈을 사용하기 (자바 구성 : 구성 스프링 데이터 JPA는 공장 빈 (XML 구성)
<jpa:repositories base-package="org.example.jpa"
factory-class="org.example.jpa.ExtendedJPARepositoryFactoryBean"/>
단계 (b)
를 사용하는)
@EnableJpaRepositories(repositoryFactoryBeanClass = ExtendedJPARepositoryFactoryBean.class)
비슷한 질문에 답 유지 : HTTP : // stackoverf low.com/questions/34528234/how-to-inject-bean-into-own-implementation-simplejparepository – Alec
나는 질문에서 불필요한 코드를 편집 한 사람이었습니다. 나는 덧붙여서 추가 코드가 문제 나 해결책에 아무런 영향을 미치지 않는다는 점을 분명히했다. 편집이 불필요하다고 생각되면 언제든지 원래 질문으로 되돌릴 수 있습니다. 아래의 내 대답을 확인하여 솔루션에 도달하고 제안 된 솔루션이 귀하에게 적합한 지 확인하기 위해 모든 추가 코드가 필요한 이유를 확인하십시오. – manish