java.lang.ClassCastException: com.sun.proxy.$Proxy27 cannot be cast to com.bbk.n002.service.QuestionService

來源:互聯網
上載者:User

標籤:cat   nal   lib   注意   強制   spec   star   ref   base   

1 嚴重: Servlet /N002-1.0 threw load() exception 2 java.lang.ClassCastException: com.sun.proxy.$Proxy27 cannot be cast to com.bbk.n002.service.QuestionService 3     at com.bbk.n002.servlet.CreateTaskQueueServlet.init(CreateTaskQueueServlet.java:28) 4     at javax.servlet.GenericServlet.init(GenericServlet.java:160) 5     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280) 6     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193) 7     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088) 8     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176) 9     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)10     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)11     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)12     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)13     at java.util.concurrent.FutureTask.run(Unknown Source)14     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)15     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)16     at java.lang.Thread.run(Unknown Source)

  

Spring的文檔中這麼寫的:Spring AOP部分使用JDK動態代理或者CGLIB來為目標對象建立代理。如果被代理的目標實現了至少一個介面,則會使用JDK動態代理。所有該目標類型實現的介面都將被代理。例如,我自己編寫的ServiceImpl類實現了Service介面,就在使用getBean()時,就不能使用ServiceImpl去接收,而要使用Service這個介面去接收

    SalaryService salaryservice =(SalaryService) new ClassPathXmlApplicationContext("Bean.xml").getBean("salaryservice");

  

 

若該目標對象沒有實現任何介面,則建立一個CGLIB代理。

        所以,解決辦法是,如果用JDK動態代理,就必須為被代理的目標實現一個介面(要注意的地方是:需要將ctx.getBean()方法的傳回值用介面類型接收);如果使用CGLIB強制代理,就必選事先將CGLIB包匯入項目,設定beanNameAutoProxyCreator的proxyTargetClass屬性為true。

這裡DeviceService實現了介面IDeviceService,所以會使用JDK動態代理,從而使(DeviceService) deviceService強制轉換的時候報錯(因為實現IDeviceService介面的代理類是屬於DeviceService子類)。因此需要使用CGLIB強制代理。需要在springContext.xml中增加如下配置:


[html]
<aop:aspectj-autoproxy proxy-target-class="true"/> 

<aop:aspectj-autoproxy proxy-target-class="true"/>

java.lang.ClassCastException: com.sun.proxy.$Proxy27 cannot be cast to com.bbk.n002.service.QuestionService

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.