0

我正在编写一个所有 Hibernate DAO 类都将继承的通用 Hibernate DAO 类。我正在尝试使用 spring 为类注入依赖项,但出现异常。

@Repository
public class HibernateDaoImpl <T>  implements Dao<T>{
    @Autowired
    private SessionFactory sessionFactory;
    @Autowired
    private Class<T> clazz;

     //setter & getter

    public HibernateDaoImpl (Class<T> clazz)
    {
      this.clazz = clazz;
    }
    public Session getCurrentSession ()
    {
        return sessionFactory.getCurrentSession();
    }

    public void save(T t) 
    {
        getCurrentSession().save(t);
    }

    public void update(T t) 
    {
        getCurrentSession().update(t);
    }


    @SuppressWarnings("unchecked")
    public T findById(Object object)
    {
        return (T) getCurrentSession().get(clazz, (Serializable)object);
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll(int page, int maxResult) 
    {
        return getCurrentSession().createQuery(String.format("FROM %s", clazz.getSimpleName())).list();
    }

我的派生类

public class SubscriberHibernateDao extends HibernateDaoImpl<Subscriber> implements SubscriberDao {

    public SubscriberHibernateDao ()
    {
        super(Subscriber.class);
    }
}

我的spring-xml

<bean id="subscriber" class="com.example.model.Subscriber" autowire="byName">
    <property name="email" value="mdennis10"></property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/kyro"/>
    <property name="username" value="root"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.kyrogaming.model"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<bean id="subcriberDao" class="com.example.dao.SubscriberHibernateDao">
 <property name="clazz" value="com.example.model.Subscriber"></property>
</bean>

当我运行它时,我得到以下堆栈跟踪:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Class com.example.dao.HibernateDaoImpl.clazz; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.kyrogaming.test.BeanTest.test(BeanTest.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

引起:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private java.lang.Class com.example.dao.HibernateDaoImpl.clazz;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type of [java.lang.Class] found for dependency: 预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释: org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514) 中的 {@org.springframework.beans.factory.annotation.Autowired(required=true)}。 beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor。postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) ... 36 更多 原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到符合条件的类型 [java.lang.Class] 的 bean 依赖:预计至少有 1 个 bean此依赖项的自动装配候选者。依赖注释:在 org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) 在 org.springframework.beans 的 {@org.springframework.beans.factory.annotation.Autowired(required=true)}。 factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) 在 org.springframework.beans。

我怎样才能解决这个问题。

4

2 回答 2

2
@Autowired 
private Class<T> clazz;

您代码中的这一行将永远无法工作,因为 spring 不知道要自动装配什么。您只能按类型或工人阶级自动装配,最好是类型。

您需要将该类包装在一个包装器对象中,以便您可以按类型执行 Autowire,然后将该类型注入 DAO。

例子

@Autowired
private Entity<T> entity;
于 2013-09-23T03:08:55.950 回答
0

您已经clazz通过 setter-injection 设置字段(在您的 中spring-xml):

<property name="clazz" value="com.example.model.Subscriber"></property>

所以没有必要@Autowired在场上clazz。但是,您需要为 field 添加一个 setter clazz,否则 Spring 将无法执行 Setter-Injection。

于 2018-10-04T14:26:42.583 回答