从Spring Data Jpa使用CrudRepository时如何修复NoSuchBeanDefinitionException?

时间:2017-03-18 08:12:08

标签: java spring hibernate spring-data-jpa

Collegues,我正在尝试使用Spring Crud Repository从数据库获取数据:

@Component
public interface AssetsGapSortDAO  extends CrudRepository<AssetsGapSortEntity, Integer> {
   AssetsGapSortEntity getByIsin(String ISIN);
}

JPA实体看起来像:

@Entity
@Table(name = "Assets", schema = "dbo", catalog = "")
public class AssetsGapSortEntity {
    private BigInteger id;

    private String shortName;
    private String isin;
    private int registrationDate;
    /*Some other properties*/

    @Basic
    @Column(name = "id")
    public BigInteger getId() {
        return id;
    }

    public void setId(BigInteger id) {
        this.id = id;
    }


    @Id
    @Column(name = "ShortName")
    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }


    @Basic
    @Column(name = "ISIN")
    public String getIsin() {
        return isin;
    }

    public void setIsin(String isin) {
        this.isin = isin;
    }

    /*Equals and hashcode methods*/


    @Override
    public String toString() {
        ToStringStyle style = new NotNullToStringStyle();
        return ToStringBuilder.reflectionToString(this, style);
    }


}

当我运行jUnit测试时:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = OlmeSmbConfig.class, loader = AnnotationConfigContextLoader.class)
public class AssetsGapSortDAOTest {
    private static final Logger log = LoggerFactory.getLogger(ExtractionsDAOTest.class);

    @Autowired
    AssetsGapSortDAO assetsGapSortDAO;

    @Test
    public void getByIsin() throws Exception {
        log.info(assetsGapSortDAO.getByIsin("TT0W3888254").toString());
    }

}

我收到了naxt stackTrace:

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
....
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'assetInfoLoader': Unsatisfied dependency expressed through field 'assetsGapSortDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.comp.olme.jpa.dao.GapSort.AssetsGapSortDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    ....
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 29 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.comp.olme.jpa.dao.GapSort.AssetsGapSortDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1102)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 45 more

我的配置如下:

@Configuration
@EnableTransactionManagement
@ComponentScan (basePackages = {"com.comp.olme"})
@PropertySource("classpath:OlmeSmb-${env}.properties")
@EnableScheduling
public class OlmeSmbConfig {
/*There are DataSource, EntityManagerFactory beans etc....*/
}

当我使用简单的JPA时,一切正常,但我想尝试CrudRepository。 所以问题是为什么我收到NoSuchBeanDefinitionException以及如何解决它? 谢谢。

更新

根据@javaguy建议我添加到我的配置@EnableJpaRepositories注释:

@EnableJpaRepositories(basePackages="com.comp.olme", entityManagerFactoryRef ="emGapSort", transactionManagerRef = "txManagerGapSort")

和“NoSuchBeanDefinitionException”已修复,但新的提升:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#3e4e8fdf': Unsatisfied dependency expressed through method 'createSharedEntityManager' parameter 0: 
Could not convert argument value of type [com.sun.proxy.$Proxy44] to required type [javax.persistence.EntityManagerFactory]: 
Failed to convert value of type 'com.sun.proxy.$Proxy44 implementing org.hibernate.jpa.HibernateEntityManager,org.springframework.orm.jpa.EntityManagerProxy' to required type 'javax.persistence.EntityManagerFactory';
nested exception is java.lang.IllegalStateException: 
Cannot convert value of type 'com.sun.proxy.$Proxy44 implementing org.hibernate.jpa.HibernateEntityManager,org.springframework.orm.jpa.EntityManagerProxy' to required type 'javax.persistence.EntityManagerFactory': 
no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1028)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299)
    ... 58 more

可能是因为我在Spring Config中有多个数据源(不同的数据库有两个)?怎么解决? 对不起,如果超出范围...

2 个答案:

答案 0 :(得分:2)

spring-data自动为您的DAO(存储库)类提供实现(即,为您的AssetsGapSortDAO接口),但您需要告诉您可以找到存储库类的位置。因此,将@EnableJpaRepositories(basePackages="com.yourproject")类级别注释添加到OlmeSmbConfig类以扫描存储库。

我建议您参考here,以便更好地了解弹簧数据的工作原理。

此外,我建议您将AssetsGapSortDAO注释为@Repository而不是@Component(尽管从技术上讲它是有效的,标记@Repository使存储库/ dao类更清晰)。

答案 1 :(得分:0)

我必须将这些注释添加到主应用程序类中,这使整个过程变得不同,它有效(即使项目中有多个根)

@EnableJpaRepositories("com.yourproject") @EntityScan(basePackages="com.yourproject ... packageWithArgumentTypesToCrudRepository")