春季jpa自定义存储库不工作 [英] spring jpa custom repository not working

查看:86
本文介绍了春季jpa自定义存储库不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用spring创建一个自定义存储库实现并获取以下
错误:

 造成的:org .springframework.beans.factory.NoSuchBeanDefinitionException:否
类型为[com.mynamespace.domain.repository.GenericRepositoryImpl]的符合条件的bean
符合依赖关系:预计至少有1个符合自动装配条件的bean
这种依赖的候选人。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

这是我的代码(从 https://下载它dl.dropboxusercontent.com/u/11115278/src-spring-problem/SpringSimple.zip.renameit ):

  public class GenericRepositoryImpl< T,ID extends Serializable>扩展
SimpleJpaRepository< T,ID>实现GenericRepository< T,ID> {

private static final long serialVersionUID = 1L;

私人EntityManager entityManager;
私人课程< T> domainClass;

public GenericRepositoryImpl(Class< T> domainClass,EntityManager entityManager){

super(domainClass,entityManager);

this.entityManager = entityManager;
this.domainClass = domainClass;
}

public List< T> someCustomMethod(Long orgId){

return super.findAll();


$ / code $ / pre
$ b $ p

中间界面

  @NoRepositoryBean 
public interface GenericRepository< T,ID extends Serializable>扩展JpaRepository< T,ID> {

列表< T> someCustomMethod(Long orgId);





$ p自定义工厂bean


  public class GenericRepositoryFactoryBean< R extends JpaRepository< T,I>,T,I extends Serializable> 
扩展JpaRepositoryFactoryBean< R,T,I> {

静态记录器记录器= LoggerFactory.getLogger(GenericRepositoryFactoryBean.class);

protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager){

logger.debug(#### GenericRepositoryFactoryBean:createRepositoryFactory ############## ###);
返回新的GenericRepositoryFactory(entityManager);
}

protected static class GenericRepositoryFactory< T,I extends Serializable>扩展JpaRepositoryFactory {

私有EntityManager entityManager;

public GenericRepositoryFactory(EntityManager entityManager){
super(entityManager);
logger.debug(#### GenericRepositoryFactory:createRepositoryFactory #################);
this.entityManager = entityManager;


保护对象getTargetRepository(RepositoryMetadata元数据){
logger.debug(#### GenericRepositoryFactory:getTargetRepository ############# ####);
logger.debug(#### GenericRepositoryFactory:getTargetRepository metadata.domainType - %1 entityManager - %2,metadata.getDomainType(),entityManager); $(b)返回新的GenericRepositoryImpl< T,I>((Class )metadata.getDomainType(),entityManager);
}

protected Class<?> getRepositoryBaseClass(RepositoryMetadata元数据){
logger.debug(#### GenericRepositoryFactory:getRepositoryBaseClass #################);
// RepositoryMetadata可以安全地忽略,它被JpaRepositoryFactory
//用来检查QueryDslJpaRepository的超出范围。
返回GenericRepositoryImpl.class;



Spring配置

 < jpa:repositories base-package =com.mynamespace.domain.repository
factory-class =com.mynamespace .domain.factory.GenericRepositoryFactoryBean/>

< bean id =entityManagerFactory
class =org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean>
< property name =persistenceUnitNamevalue =Mypu/>
< property name =dataSource>
< jee:jndi-lookup id =dataSorucejndi-name =java:comp / env / jdbc / MyDS/>
< / property>
< property name =packagesToScanvalue =com.mynamespace.domain.model/>
< property name =jpaVendorAdapter>
< bean class =org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter>
< property name =generateDdlvalue =false/>
< property name =showSqlvalue =false/>
< property name =databasePlatformvalue =org.hibernate.dialect.PostgreSQLDialect/>
< / bean>
< / property>
< / bean>

<! - TransactionManager - >
< bean id =txManagerclass =org.springframework.orm.jpa.JpaTransactionManager>
< property name =entityManagerFactoryref =entityManagerFactory/>
< / bean>

< tx:annotation-driven transaction-manager =txManager/>

其他信息:我正在使用Spring MVC,我有一个用于Spring MVC的配置文件,对于数据,这是我的Spring MVC文件:

 < beans xmlns =http://www.springframework.org/ schema / beansxmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xmlns:mvc =http://www.springframework.org/schema/mvcxmlns: context =http://www.springframework.org/schema/context
xsi:schemaLocation =http://www.springframework.org/schema/mvc http://www.springframework.org/schema /mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http: //www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">

< import resource =classpath:spring / *。xml/>
< context:component-scan base-package =com.mynamespace.controllers/>

< mvc:annotation-driven />
< mvc:resources mapping =/ css / **location =/ WEB-INF / resources / css //>
< mvc:resources mapping =/ js / **location =/ WEB-INF / resources / js //>
< mvc:resources mapping =/ images / **location =/ WEB-INF / resources / images //>
< mvc:resources mapping =/ font / **location =/ WEB-INF / resources / font //>

< bean class =org.springframework.web.servlet.view.InternalResourceViewResolver>
<! - 示例:'showMessage'的逻辑视图名称被映射到'/WEB-INF/jsp/showMessage.jsp' - >
< property name =prefixvalue =/ WEB-INF / view //>
< property name =suffixvalue =。jsp/>
< / bean>

< / beans>

不工作:(任何帮助?

解决方案

这个异常似乎表明您从应用程序类中的某个注入点引用了 GenericRepositoryImpl 。并不能完全显示出原来的位置,添加更多的原始堆栈跟踪可能有助于确定问题的根本原因,它绝对是一个试图直接自动调用实现类的应用程序组件。



确保你仍然让你的应用程序库扩展 GenericRepository ,并且只将它们注入到你的服务,控制器等中。



编辑:下面的评论线索是由于对提供的示例代码的误解而产生的。


Trying to create a custom repository implementation with spring and getting the following error:

caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type [com.mynamespace.domain.repository.GenericRepositoryImpl] 
  found for dependency: expected at least 1 bean which qualifies as autowire 
  candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 

Here is my code (download it from https://dl.dropboxusercontent.com/u/11115278/src-spring-problem/SpringSimple.zip.renameit):

public class GenericRepositoryImpl<T, ID extends Serializable> extends
        SimpleJpaRepository<T, ID> implements GenericRepository<T, ID> {

    private static final long serialVersionUID = 1L;

    private EntityManager entityManager;
    private Class<T> domainClass;

    public GenericRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {

        super(domainClass, entityManager);

        this.entityManager = entityManager;
        this.domainClass = domainClass;
    }

    public List<T> someCustomMethod(Long orgId) {

        return super.findAll();
    }
}

The intermediate interface

@NoRepositoryBean
public interface GenericRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {

  List<T> someCustomMethod(Long orgId);
}

Custom Factory bean

public class GenericRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
  extends JpaRepositoryFactoryBean<R, T, I> {

  static Logger logger = LoggerFactory.getLogger(GenericRepositoryFactoryBean.class);

  protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {

    logger.debug("#### GenericRepositoryFactoryBean : createRepositoryFactory #################");
    return new GenericRepositoryFactory(entityManager);
  }

  protected static class GenericRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

    private EntityManager entityManager;

    public GenericRepositoryFactory(EntityManager entityManager) {
      super(entityManager);
      logger.debug("#### GenericRepositoryFactory : createRepositoryFactory #################");
      this.entityManager = entityManager;
    }

    protected Object getTargetRepository(RepositoryMetadata metadata) {
      logger.debug("#### GenericRepositoryFactory : getTargetRepository #################");
       logger.debug("#### GenericRepositoryFactory : getTargetRepository metadata.domainType - %1 entityManager - %2",metadata.getDomainType(),entityManager);
      return new GenericRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
    }

    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
      logger.debug("#### GenericRepositoryFactory : getRepositoryBaseClass #################");
      // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
      // to check for QueryDslJpaRepository's which is out of scope.
      return GenericRepositoryImpl.class;
    }
  }
}

Spring configuration

<jpa:repositories base-package="com.mynamespace.domain.repository" 
  factory-class="com.mynamespace.domain.factory.GenericRepositoryFactoryBean"/> 

<bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="persistenceUnitName" value="Mypu" />
  <property name="dataSource" >
    <jee:jndi-lookup id="dataSoruce" jndi-name="java:comp/env/jdbc/MyDS" />
  </property>
  <property name="packagesToScan" value="com.mynamespace.domain.model" />
  <property name="jpaVendorAdapter">
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
          <property name="generateDdl" value="false"/>
          <property name="showSql" value="false"/>
          <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
      </bean>
  </property>
</bean>

<!--TransactionManager-->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="txManager"/>

Additional info: I'm using Spring MVC, I have a config file for Spring MVC and another files for data and this is my Spring MVC file:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:spring/*.xml"/>
    <context:component-scan base-package="com.mynamespace.controllers"/>

    <mvc:annotation-driven />
    <mvc:resources mapping="/css/**" location="/WEB-INF/resources/css/" />
    <mvc:resources mapping="/js/**" location="/WEB-INF/resources/js/" />
    <mvc:resources mapping="/images/**" location="/WEB-INF/resources/images/" />
    <mvc:resources mapping="/font/**" location="/WEB-INF/resources/font/" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>

Is not working :( any help?

解决方案

The exception seems to indicate that you refer to the GenericRepositoryImpl from an injection point somewhere in your application classes. The samples unfortunately don't show where from exactly. Adding more of the original stack trace might help to identify the root cause of the problem. It's definitely an application component trying to autowire the implementation class directly.

Make sure you still you let your application repositories extend GenericRepository and only inject those into your services, controllers, etc.

EDIT: The comment thread below resulted from a misunderstanding regarding the provided sample code.

这篇关于春季jpa自定义存储库不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆