spring使用中报Cannot proxy target class because CGLIB2 is not available错

来源:互联网 发布:java web项目开发2017 编辑:程序博客网 时间:2024/06/06 14:10


发现问题

public interface StudentService
{
 void add();
}

@Service
public class StudentServiceImpl implements StudentService
{
 void add(){  }
}

public class StudentAction extends ActionSupport
{
 private StudentService studentService;

 @Resource
 public void setStudentService()
 {

 }
}

以上描述了一个很简单的注入过程。但若StudentServiceImpl没有实现StudentService接口

@Service
public class StudentServiceImpl
{
 void add(){  }
}

在使用的时候会报Cannot proxy target class because CGLIB2 is not available

 

 

问题原因

代理为控制要访问的目标对象提供了一种途径。当访问对象时,它引入了一个间接的层。JDK自从1.3版本开始,就引入了动态代理,并且经常被用来动态地创建代理。JDK的动态代理用起来非常简单,但它有一个限制,就是使用动态代理的对象必须实现一个或多个接口。

 


解决办法

方案一 使实际的类实现某个接口
方案二 使用CGLIB包

cglib是一个开源项,一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口。Hibernate用它来实现PO字节码的动态生成。

 

参考地址:http://baike.baidu.com/view/1254036.htm