views:

37

answers:

1

Hi,

I'm trying to instantiate a generic class in Spring, but I get following exception:

Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class football.dao.jpa.GenericJpaDAO]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given:

This is the XML configuration for Spring container:

<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>

This is the generic class:

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

}

I'm not really sure what could be causing this. I would appreciate any ideas.

A: 

This problem is not related to generics, it's a limitation of Spring AOP.

If aspects (including @Transactional aspect) are applied to the class using CGLIB proxy (this happens if target class doesn't implement any interfaces or if AOP is configured with proxy-target-class = "true"), no-argument constructor is required:

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

  public GenericJpaDAO() {}

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

See also:

axtavt
Thanks a lot! I wasn't aware of that.
stoupa