793
技術社區[雲棲]
spring使用中報Cannot proxy target class because CGLIB2 is not available錯
發現問題
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字節碼的動態生成。
參考地址:https://baike.baidu.com/view/1254036.htm
最後更新:2017-04-03 07:57:23