在 Spring 中实例化泛型类 bean 时出现问题

2023-12-25

我试图在 Spring 中实例化一个泛型类,但出现以下异常:

bean 初始化失败;嵌套异常是 org.springframework.aop.framework.AopConfigException:无法生成类[类football.dao.jpa.GenericJpaDAO]的CGLIB子类:此问题的常见原因包括使用最终类或不可见类;嵌套异常是 java.lang.IllegalArgumentException:超类没有 null 构造函数,但没有给出参数:

这是 Spring 容器的 XML 配置:

<bean id="clubDAO" class="football.dao.jpa.GenericJpaDAO">
    <constructor-arg type="EntityManagerFactory" ref="entityManagerFactory"/>
    <constructor-arg type="Class" value="football.model.entities.ClubEntity"/>
    <constructor-arg type="String" value="ClubEntity"/>
</bean>

这是通用类:

public class GenericJpaDAO <T extends HavingID> {

  private EntityManager em;
  private Class entityClass;
  private String entityName;

  public GenericJpaDAO( Class entityClass, String entityName,
        EntityManagerFactory emFactory ) {
    this.entityClass = entityClass;
    this.entityName = entityName;
    em = emFactory.createEntityManager();
  }

  @Transactional
  public void create( T entity ) {
      em.persist( entity );
  }
  // more methods

}

我不太确定是什么原因造成的。我将不胜感激任何想法。


这个问题与泛型无关,它是 Spring AOP 的限制。

如果方面(包括@Transactional方面)使用CGLIB代理应用于类(如果目标类没有实现任何接口或者AOP配置为proxy-target-class = "true"),需要无参构造函数:

public class GenericJpaDAO <T extends HavingID> { 
  ...

  public GenericJpaDAO() {}

  public GenericJpaDAO( Class entityClass, String entityName, 
        EntityManagerFactory emFactory ) { ... } 
  ...
}

也可以看看:

  • 7.6 代理机制 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-proxying
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Spring 中实例化泛型类 bean 时出现问题 的相关文章

随机推荐