一.問(wèn)題分析
1.報(bào)錯(cuò)背景
遇到這個(gè)問(wèn)題是在類型轉(zhuǎn)換時(shí),如下:
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
PassApiServiceImpl service = (PassApiServiceImpl) wac.getBean("passApiService");
2.錯(cuò)誤分析
2.1 知識(shí)點(diǎn):
Spring AOP實(shí)現(xiàn)方式有兩種
1:使用JDK動(dòng)態(tài)代理,如果被代理的目標(biāo)實(shí)現(xiàn)了至少一個(gè)接口,則會(huì)使用JDK動(dòng)態(tài)代理,所有該目標(biāo)類型實(shí)現(xiàn)的接口都將被代理。
2:通過(guò)CGLIB來(lái)為目標(biāo)對(duì)象創(chuàng)建代理,若該目標(biāo)對(duì)象沒有實(shí)現(xiàn)任何接口,則創(chuàng)建一個(gè)CGLIB代理,創(chuàng)建的代理類是目標(biāo)類的子類。
2.2 錯(cuò)誤分析
那根據(jù)我遇到的情況分析,我的PassApiServiceImpl實(shí)現(xiàn)了PassApiService接口,aop應(yīng)該是使用了JDK Proxy。
而報(bào)錯(cuò)的原因,是不能用接口的實(shí)現(xiàn)類(PassApiServiceImpl)來(lái)轉(zhuǎn)換Proxy的實(shí)現(xiàn)類,它們是同級(jí),應(yīng)該用共同的接口(PassApiService)來(lái)轉(zhuǎn)換。
二.解決方案
1.使用接口來(lái)進(jìn)行類型轉(zhuǎn)換,將PassApiServiceImpl改為PassApiService。
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
PassApiService service = (PassApiService) wac.getBean("passApiService");
三.其他解決方案
看到有一種解決方案是強(qiáng)制使用CGLIB創(chuàng)建代理,需要引用jar包并修改spring配置文件。我沒有使用,有機(jī)會(huì)再進(jìn)行了解吧。