2016-10-05 6 views
1

SimpleJpaRepository을 덮어 쓸 때 @Autowired을 통해 다른 빈을 추가해도 작동하지 않습니다. 이 경우 콩을 주입 할 수 있습니까?@Autowired가 SimpleJpaRepository 확장자에서 작동하지 않습니다.

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

비슷한 질문에 답 유지 : HTTP : // stackoverf low.com/questions/34528234/how-to-inject-bean-into-own-implementation-simplejparepository – Alec

+1

나는 질문에서 불필요한 코드를 편집 한 사람이었습니다. 나는 덧붙여서 추가 코드가 문제 나 해결책에 아무런 영향을 미치지 않는다는 점을 분명히했다. 편집이 불필요하다고 생각되면 언제든지 원래 질문으로 되돌릴 수 있습니다. 아래의 내 대답을 확인하여 솔루션에 도달하고 제안 된 솔루션이 귀하에게 적합한 지 확인하기 위해 모든 추가 코드가 필요한 이유를 확인하십시오. – manish

답변

2

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) 
+0

사실 저는이 솔루션에 대해 생각하고 있었지만 스프링 데이터 작성자가 고려하지 않은 이유에 대해 궁금 해서요. 추가 동작이 필요할 수 있습니다. 솔루션은 완벽하게 작동하지만 여전히 해결 방법처럼 보입니다. 어쨌든 받아 들인다. – Alec

-1

봄은 당신이 @Component로 주석을 달 필요가 당신의 DAO 안에 뭔가를 주입 할 필요가 있음을 알려하기 위해 : 여기에 구현입니다.

자세한 내용은 여기 http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-spring-beans-and-dependency-injection.html에서 확인할 수 있습니다.

+0

예, 저는 기본을 알고 있습니다 :) 그러나이 특별한 경우에는 @Component로 주석을 달았습니다 - 바로 알겠습니다 com.example.model.dao.BaseDAO에서 생성자의 매개 변수 0에 'org.springframework'유형의 bean이 필요했습니다. .data.jpa.repository.support.JpaEntityInformation '을 찾을 수 없습니다. 그리고 앱이 분명히 시작되지 않습니다. – Alec

관련 문제