Spring 3.0+ Hibernate 3.3 泛型 注解管理Bean 出现问题 郁闷!

参照网上的Demo 自己也弄了个泛型注解 BaseDao 里面 的gedao 是null 高手们给看一下
[code="java"]package com.zw.core;

import java.io.Serializable;
import java.util.List;

public interface IBaseDao {
public T getById(PK id);
public List getAll();
public T load(PK id);
public void load(T entityObject, PK id);
public void delete(T entityObject);
public void deleteById(PK id);
public void refresh(T entityObject);
public void evict(T entityObject);
public void save(T entityObject);
public void clear();

}[/code]
[code="java"]package com.zw.core;

import java.io.Serializable;
import java.util.List;
public class BaseDao implements IBaseDao {
protected Class entityClass;// DAO所管理的Entity类型.
private GenericEntityDao gedao;
public Class getEntityClass() {
return entityClass;
}
public void setEntityClass(Class entityClass) {
this.entityClass = entityClass;
}
public GenericEntityDao getGedao() {
return gedao;
}
public void setGedao(GenericEntityDao gedao) {
this.gedao = gedao;
}
/**
* 让spring提供构造函数注入
*/
public BaseDao(Class type) {
this.entityClass = type;
}

public BaseDao() {
}

public void delete(T entityObject) {
    gedao.delete(entityObject);
}

public void deleteById(PK id) {
    gedao.deleteById(id);
}
public void evict(T entityObject) {
    gedao.evict(entityObject);
}
public List<T> getAll() {
    return gedao.getAll();
}
public T getById(PK id) {
    return gedao.getById(id);
}
public T load(PK id) {
    return gedao.load(id);
}
public void load(T entityObject, PK id) {
    gedao.load(entityObject, id);
}
public T merge(T entityObject) {
    return gedao.merge(entityObject);
}
public void refresh(T entityObject) {
    gedao.refresh(entityObject);
}
public void save(T entityObject) {
    System.out.println("gedao:"+gedao);
    gedao.save(entityObject);
}
public void clear() {
}

}
[/code]
[code="java"]package com.zw.core;

import java.io.Serializable;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GenericEntityDao extends HibernateDaoSupport {

protected Class<T> entityClass;// DAO所管理的Entity类型.
public GenericEntityDao() {
}

public GenericEntityDao(Class<T> entityClass) {
    this.entityClass = entityClass;
}
@SuppressWarnings("unchecked")
public T getById(PK id) {
    return (T) this.getHibernateTemplate().get(this.entityClass, id);
}
@SuppressWarnings("unchecked")
public List<T> getAll() {
    return (List<T>) (this.getHibernateTemplate().loadAll(this.entityClass));
}

@SuppressWarnings("unchecked")
public T load(PK id) {
    return (T) this.getHibernateTemplate().load(this.entityClass, id);
}

public void load(T entityObject, PK id) {
    this.getHibernateTemplate().load(entityObject, id);
}

public void delete(T entityObject) {
    this.getHibernateTemplate().delete(entityObject);
}
public void deleteById(PK id) {
    this.delete(this.getById(id));
}
public void refresh(T entityObject) {
    this.getHibernateTemplate().refresh(entityObject);
}

public void evict(T entityObject) {
    this.getHibernateTemplate().evict(entityObject);
}

public void save(T entityObject) {

    this.getHibernateTemplate().saveOrUpdate(entityObject);
}
@SuppressWarnings("unchecked")
public T merge(T entityObject) {
    return (T) this.getHibernateTemplate().merge(entityObject);
}

}
[/code]

ToplMSoftDAO

[code="java"]package com.zw.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import com.zw.core.BaseDao;
import com.zw.domain.ToplMSoft;
@Repository("toplMSoftDAO")
public class ToplMSoftDAO extends BaseDao {
private static final Log log = LogFactory.getLog(ToplMSoftDAO.class);
}
[/code]

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

<!-- 使用外部文件配置数据源的属性 -->



<!-- 外部文件地址 -->
classpath:database_conn.properties




<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="driverClass" value="${driverClassName}" />
    <property name="jdbcUrl" value="${url}" />
    <property name="user" value="${username}" />
    <property name="password" value="${password}" />
    <property name="minPoolSize" value="5" />
    <property name="maxPoolSize" value="20" />
    <property name="initialPoolSize" value="10" />
    <property name="maxIdleTime" value="60" />
    <property name="acquireIncrement" value="5" />
    <property name="maxStatements" value="0" />
    <property name="idleConnectionTestPeriod" value="60" />
    <property name="acquireRetryAttempts" value="30" />
    <property name="breakAfterAcquireFailure" value="true" />
    <property name="testConnectionOnCheckout" value="false" />
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <!-- 引用数据源 -->
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="namingStrategy">
        <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>         
            <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}
            </prop>

            <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}
            </prop>

        </props>
     </property>    
     <property name="packagesToScan" value="com.zw.domain" /> 

    <!--</property>     
    <property name="annotatedClasses">
        <list>
            <value>org.wpms.kernel.user.po.User</value>
        </list>
    </property>-->
</bean>



<!-- 定义了与实体相关的dao -->
<bean id="genericEntityDao" class="com.zw.core.GenericEntityDao"
    scope="prototype" lazy-init="true">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>
<!--使用泛型DAO作为抽象基类 abstract="true" -->
<bean id="baseDao" class="com.zw.core.BaseDao"
    abstract="true" depends-on="genericEntityDao">
    <property name="gedao">
        <ref bean="genericEntityDao" />
    </property>
</bean>

     <!-- 使Spring关注Annotation -->
  <context:annotation-config />
<!-- 让Spring通过自动扫描来查询和管理Bean -->
 <context:component-scan base-package="com.zw" />

<!--  
<bean id="toplMSoftDAO" class="com.zw.dao.ToplMSoftDAO" parent="baseDao"></bean>
<bean id="toplMSoftServiceImpl"
    class="com.zw.service.impl.ToplMSoftServiceImpl">
    <property name="toplMSoftDAO" ref="toplMSoftDAO" />
</bean> 
-->
<!--
    业务类bean的实现类标注了@Transactional注解,所以会被 tx:annotation-driven注解驱动自动织入事务增强
-->
<!-- 配置事务管理器 -->
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>
<!--注解式事务配置驱动-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
</beans>

[/code]
ToplMSoft
[code="java"]
package com.zw.domain;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "topl_m_soft", catalog = "zwtest")
public class ToplMSoft implements java.io.Serializable {
// Fields

/**
 * 
 */
private static final long serialVersionUID = -5245203859352468180L;
private Integer softkey;
private String softname;
private String softtypekey;
private String softversion;
private String softsize;
private String providername;
private String providersite;
private String downsite1;
private String softfaceurl;
private String issuestate;
private String fruntime;
private String sruntime;
private Float marketprice;
private Float storeprice;
private String ifourcommend;
private String ifspprice;
private String softenglishname;
private String runLink;
private String runnum;
private String downnum;
private String column1;
private String column2;
private String column3;
private String contact;
private Timestamp createdate;
private Timestamp updatedate;

// Constructors

/** default constructor */
public ToplMSoft() {
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "softkey", unique = true, nullable = false)
public Integer getSoftkey() {
    return this.softkey;
}

public void setSoftkey(Integer softkey) {
    this.softkey = softkey;
}

@Column(name = "softname", nullable = false, length = 100)
public String getSoftname() {
    return this.softname;
}

public void setSoftname(String softname) {
    this.softname = softname;
}

@Column(name = "softtypekey", nullable = false, length = 10)
public String getSofttypekey() {
    return this.softtypekey;
}

public void setSofttypekey(String softtypekey) {
    this.softtypekey = softtypekey;
}

@Column(name = "softversion", length = 20)
public String getSoftversion() {
    return this.softversion;
}

public void setSoftversion(String softversion) {
    this.softversion = softversion;
}

@Column(name = "softsize", length = 20)
public String getSoftsize() {
    return this.softsize;
}

public void setSoftsize(String softsize) {
    this.softsize = softsize;
}

@Column(name = "providername", length = 200)
public String getProvidername() {
    return this.providername;
}

public void setProvidername(String providername) {
    this.providername = providername;
}

@Column(name = "providersite", length = 100)
public String getProvidersite() {
    return this.providersite;
}

public void setProvidersite(String providersite) {
    this.providersite = providersite;
}

@Column(name = "downsite1", length = 300)
public String getDownsite1() {
    return this.downsite1;
}

public void setDownsite1(String downsite1) {
    this.downsite1 = downsite1;
}

@Column(name = "softfaceurl", length = 200)
public String getSoftfaceurl() {
    return this.softfaceurl;
}

public void setSoftfaceurl(String softfaceurl) {
    this.softfaceurl = softfaceurl;
}

@Column(name = "issuestate", length = 10)
public String getIssuestate() {
    return this.issuestate;
}

public void setIssuestate(String issuestate) {
    this.issuestate = issuestate;
}

@Column(name = "fruntime", length = 10)
public String getFruntime() {
    return this.fruntime;
}

public void setFruntime(String fruntime) {
    this.fruntime = fruntime;
}

@Column(name = "sruntime", length = 10)
public String getSruntime() {
    return this.sruntime;
}

public void setSruntime(String sruntime) {
    this.sruntime = sruntime;
}

@Column(name = "marketprice", precision = 10, scale = 0)
public Float getMarketprice() {
    return this.marketprice;
}

public void setMarketprice(Float marketprice) {
    this.marketprice = marketprice;
}

@Column(name = "storeprice", precision = 10, scale = 0)
public Float getStoreprice() {
    return this.storeprice;
}

public void setStoreprice(Float storeprice) {
    this.storeprice = storeprice;
}

@Column(name = "ifourcommend", length = 2)
public String getIfourcommend() {
    return this.ifourcommend;
}

public void setIfourcommend(String ifourcommend) {
    this.ifourcommend = ifourcommend;
}

@Column(name = "ifspprice", length = 2)
public String getIfspprice() {
    return this.ifspprice;
}

public void setIfspprice(String ifspprice) {
    this.ifspprice = ifspprice;
}

@Column(name = "softenglishname", length = 200)
public String getSoftenglishname() {
    return this.softenglishname;
}

public void setSoftenglishname(String softenglishname) {
    this.softenglishname = softenglishname;
}

@Column(name = "runLink", length = 300)
public String getRunLink() {
    return this.runLink;
}

public void setRunLink(String runLink) {
    this.runLink = runLink;
}

@Column(name = "runnum", length = 10)
public String getRunnum() {
    return this.runnum;
}

public void setRunnum(String runnum) {
    this.runnum = runnum;
}

@Column(name = "downnum", length = 10)
public String getDownnum() {
    return this.downnum;
}

public void setDownnum(String downnum) {
    this.downnum = downnum;
}

@Column(name = "column1", nullable = false, length = 2000)
public String getColumn1() {
    return this.column1;
}

public void setColumn1(String column1) {
    this.column1 = column1;
}

@Column(name = "column2", length = 200)
public String getColumn2() {
    return this.column2;
}

public void setColumn2(String column2) {
    this.column2 = column2;
}

@Column(name = "column3", length = 200)
public String getColumn3() {
    return this.column3;
}

public void setColumn3(String column3) {
    this.column3 = column3;
}

@Column(name = "contact", length = 2)
public String getContact() {
    return this.contact;
}

public void setContact(String contact) {
    this.contact = contact;
}

@Column(name = "createdate", length = 19)
public Timestamp getCreatedate() {
    return this.createdate;
}

public void setCreatedate(Timestamp createdate) {
    this.createdate = createdate;
}

@Column(name = "updatedate", length = 19)
public Timestamp getUpdatedate() {
    return this.updatedate;
}

public void setUpdatedate(Timestamp updatedate) {
    this.updatedate = updatedate;
}

}
[/code]
service 层
ToplMSoftService
[code="java"]
package com.zw.service;

import com.zw.domain.ToplMSoft;

public interface ToplMSoftService {
public void save(ToplMSoft tps);

}

[/code]
ToplMSoftServiceImpl

[code="java"]package com.zw.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zw.core.BaseDao;
import com.zw.core.IBaseDao;
import com.zw.domain.ToplMSoft;
import com.zw.service.ToplMSoftService;
@Transactional(readOnly = true)
//对业务类进行事务增强的标注
@Service
//声明此类为业务逻辑层的类
public class ToplMSoftServiceImpl implements ToplMSoftService {
@Resource(name ="toplMSoftDAO")
private IBaseDao toplMSoftDAO;
public IBaseDao getToplMSoftDAO() {

    return toplMSoftDAO;
}
public void setToplMSoftDAO(IBaseDao<ToplMSoft, Integer> toplMSoftDAO) {
            this.toplMSoftDAO = toplMSoftDAO;
}
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void save(ToplMSoft tps) {
    System.out.println("toplMSoftDAO:"+toplMSoftDAO);
    this.toplMSoftDAO.save(tps);
}

}
[/code]

Test:

[code="java"]
package com.zw.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.zw.domain.ToplMSoft;
import com.zw.service.ToplMSoftService;
import com.zw.service.impl.ToplMSoftServiceImpl;

public class TestHibernate {
public static void main(String[] args) {

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
ToplMSoftService dao= (ToplMSoftServiceImpl) ctx.getBean("toplMSoftServiceImpl");
//GenericEntityDao dao= (GenericEntityDao) ctx.getBean("ToplMSoftDAO");
System.out.println("1111111111:"+dao);
ToplMSoft tps=new ToplMSoft();
tps.setSoftname("测试11111111");
tps.setSofttypekey("2");
tps.setColumn1("xsdasdasdasd");
dao.save(tps);

}

}

[/code]

控制台输出
我在BaseDao save方法里面打出
System.out.println("gedao:"+gedao); 为null
[code="java"]
1111111111:com.zw.service.impl.ToplMSoftServiceImpl@6e3e5e
toplMSoftDAO:com.zw.dao.ToplMSoftDAO@10718b7
gedao:null
Exception in thread "main" java.lang.NullPointerException
at com.zw.core.BaseDao.save(BaseDao.java:60)
at com.zw.service.impl.ToplMSoftServiceImpl.save(ToplMSoftServiceImpl.java:31)
at com.zw.service.impl.ToplMSoftServiceImpl$$FastClassByCGLIB$$7aa0faa6.invoke()
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)
at com.zw.service.impl.ToplMSoftServiceImpl$$EnhancerByCGLIB$$ded4983e.save()
at com.zw.test.TestHibernate.main(TestHibernate.java:22)

[/code]

如果不用注解 直接在applicationContext.xml配置
[code="java"]

<bean id="toplMSoftDAO" class="com.zw.dao.ToplMSoftDAO" parent="baseDao"></bean>
<bean id="toplMSoftServiceImpl"
    class="com.zw.service.impl.ToplMSoftServiceImpl">
    <property name="toplMSoftDAO" ref="toplMSoftDAO" />
</bean> 

[/code]
就不会报错 可以直接插入数据.

对Spring了解的不深 比较困惑
朋友们帮忙解答一下
谢谢

2个回答

[code="java"]
package com.zw.core;

import java.io.Serializable;
import java.util.List;
public class BaseDao implements IBaseDao {
protected Class entityClass;// DAO所管理的Entity类型.
@Autowired

private GenericEntityDao gedao;
public Class getEntityClass() {
return entityClass;
}
public void setEntityClass(Class entityClass) {
this.entityClass = entityClass;
}
public GenericEntityDao getGedao() {
return gedao;
}
public void setGedao(GenericEntityDao gedao) {
this.gedao = gedao;
}
/**
* 让spring提供构造函数注入
*/
public BaseDao(Class type) {
this.entityClass = type;
}

public BaseDao() {
}

public void delete(T entityObject) {
    gedao.delete(entityObject);
}

public void deleteById(PK id) {
    gedao.deleteById(id);
}
public void evict(T entityObject) {
    gedao.evict(entityObject);
}
public List<T> getAll() {
    return gedao.getAll();
}
public T getById(PK id) {
    return gedao.getById(id);
}
public T load(PK id) {
    return gedao.load(id);
}
public void load(T entityObject, PK id) {
    gedao.load(entityObject, id);
}
public T merge(T entityObject) {
    return gedao.merge(entityObject);
}
public void refresh(T entityObject) {
    gedao.refresh(entityObject);
}
public void save(T entityObject) {
    System.out.println("gedao:"+gedao);
    gedao.save(entityObject);
}
public void clear() {
}

}

[/code]

问题就是你用注释并没有在哪个地方注入genericEntityDao

你却是在配置文件里去定义这个bean,
<!-- 定义了与实体相关的dao -->

scope="prototype" lazy-init="true">









<!--使用泛型DAO作为抽象基类 abstract="true" -->

abstract="true" depends-on="genericEntityDao">







而@Repository("toplMSoftDAO")

public class ToplMSoftDAO extends BaseDao {

private static final Log log = LogFactory.getLog(ToplMSoftDAO.class);

}

这里却没有注入genericEntityDao,它怎么知道这个呢

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问