【问题标题】:Problem instantiating generic class bean in Spring在 Spring 中实例化泛型类 bean 的问题
【发布时间】:2023-04-10 11:06:01
【问题描述】:

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

bean 初始化失败;嵌套异常是 org.springframework.aop.framework.AopConfigException:无法生成类 [class football.dao.jpa.GenericJpaDAO] 的 CGLIB 子类:此问题的常见原因包括使用最终类或不可见类;嵌套异常是 java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments are given:

这是 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 generics dependency-injection


    【解决方案1】:

    这个问题与泛型无关,是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 ) { ... } 
      ...
    }
    

    另请参阅:

    【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2013-10-03
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多