SpringData&的通用类实现QueryDSL服务

时间:2015-12-11 16:45:43

标签: java spring generics querydsl

我有一堆服务类,它们具有扩展JpaRepository和QueryDslPredicateExecutor的存储库。 除了它处理的实体之外,服务类中的方法是相同的。我正在努力创造 一个通用服务类,但我得到一个“注入资源依赖关系失败;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到[pkg.BaseRepository]类型的限定bean:期望至少有一个符合条件的bean作为此依赖关系的autowire候选者“。

以下是我的课程:

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include "Vsstyle.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------


__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  Image1->Canvas->Brush->Color = clBtnFace;
  Image1->Canvas->FillRect(Image1->ClientRect);

  OSVERSIONINFO verwin;
  verwin.dwOSVersionInfoSize=sizeof(verwin);
  if (GetVersionEx(&verwin))
  {
    //Check  the Windows version
    if (verwin.dwMajorVersion >= 6) // is Vista at least?
    {
      HTHEME hTheme = OpenThemeData(Handle, VSCLASS_TASKDIALOG);
      if (hTheme)
      {
          SIZE s;
          //get the size of the  TDLG_EXPANDOBUTTON
          if (GetThemePartSize(hTheme, Image1->Canvas->Handle, TDLG_EXPANDOBUTTON, TDLGEBS_NORMAL, NULL, TS_TRUE, &s) == S_OK)
          {
              TRect pRect = Rect(0, 0, s.cx, s.cy);
              DrawThemeBackground(hTheme, Image1->Canvas->Handle, TDLG_EXPANDOBUTTON, TDLGEBS_NORMAL, &pRect, NULL);
           }
      }
    }
    else
    {
      HTHEME hTheme = OpenThemeData(Handle, VSCLASS_EXPLORERBAR);
      if (hTheme)
      {
          SIZE s;
          //get the size of the  EBP_NORMALGROUPEXPAND
          if (GetThemePartSize(hTheme, Image1->Canvas->Handle, EBP_NORMALGROUPEXPAND, EBHC_NORMAL, NULL, TS_TRUE, &s) == S_OK)
          {
              TRect pRect = Rect(0, 0, s.cx, s.cy);
              DrawThemeBackground(hTheme, Image1->Canvas->Handle, EBP_NORMALGROUPEXPAND, EBHC_NORMAL, &pRect, NULL);
           }
      }
    }
  }
}

... 以及更多XxxRepository接口

//BaseRepository.java
@NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T, Long>, QueryDslPredicateExecutor<T> {}

//RegionRepository.java
@Repository
public interface RegionRepository<Region> extends JpaRepository<Region, Long>, QueryDslPredicateExecutor<Region> {}

//ProvinceRepository.java
@Repository
public interface ProvinceRepository<Province> extends JpaRepository<Province, Long>, QueryDslPredicateExecutor<Province> {}

我的persistence.xml

//AbstractBaseService.java
public abstract class AbstractBaseService<T>{
    @Autowired 
    private BaseRepository<T> repository;

    public void add(T entity) {
        System.out.println("Adding entity " + entity.getClass());
    }

    public T retrieve(Long id) {
        System.out.println("Retrieving region with dbId = " + id);
        return repository.findOne(id);
    }

    public List<T> findAll() {
        return repository.findAll();
    }
    ...
    //some other methods

}

//RegionService.java
@Service("regService")
public class RegionService extends AbstractBaseService<Region> {}

//ProvinceService.java
@Service("provService")
public class ProvinceService extends AbstractBaseService<Province> {}


@Controller
public class MyController {

    public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("/spring/application-context.xml");

        MyController controller = new MyController();
        controller.run(context);
    }

    public void run(ApplicationContext context) {       
        RegionService regService =  (RegionService)context.getBean("regService");
        Region reg = regService.retrieve(1L);
    }
}

以下是MyController运行时的错误日志。

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
      http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit name="generics" transaction-type="RESOURCE_LOCAL">      
        <properties>
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
        </properties>
    </persistence-unit>
</persistence>

application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/data/jpa 
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
    <context:component-scan base-package="com.dreamcorps.gen" />

    <bean id="placeholderConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:spring/db.properties" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database"           value="${jpa.dbVendor}" />
                <property name="databasePlatform"   value="${jpa.dialect}"  />
                <property name="showSql"            value="${jpa.showSql}"  />  
                <property name="generateDdl"        value="false" />
            </bean>
        </property> 
        <property name="persistenceUnitName" value="generics" />    
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <!-- access -->
        <property name="driverClass"                value="${jdbc.driver}"/>
        <property name="jdbcUrl"                    value="${jdbc.url}"/>
        <property name="user"                       value="${jdbc.username}"/>
        <property name="password"                   value="${jdbc.password}"/>

        <!-- pool sizing -->
        <property name="initialPoolSize"            value="${c3p0.initialPoolSize}"/>
        <property name="minPoolSize"                value="${c3p0.minPoolSize}"/>
        <property name="maxPoolSize"                value="${c3p0.maxPoolSize}"/>
        <property name="acquireIncrement"           value="${c3p0.acquireIncrement}"/>
        <property name="maxStatements"              value="${c3p0.maxStatements}"/>

    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    </bean>

    <tx:annotation-driven />
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <jpa:repositories base-package="com.dreamcorps.gen" />

</beans>

非常感谢任何帮助。

提前致谢, 马里奥

2 个答案:

答案 0 :(得分:0)

//RegionRepository.java
@Repository
public interface RegionRepository<Region> extends JpaRepository<Region, Long>, QueryDslPredicateExecutor<Region> {}
                                  ^^^^^^ Here you are actually making a new Type Variable, which is bounded to Object.

您正在创建新的类型变量,这实际上隐藏了您为其创建存储库的类名。

答案 1 :(得分:0)

我终于能够完成我原来的工作了。缺少的是BaseRepository.java接口上的注释@NoRepositoryBean和上面编辑的RegionRepository / ProvinceRepository接口上的@Repository注释。