Exception in thread “main“ java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to XXX

:
note that the following two errors may be caused by not properly configuring the values of proxy-target-class:
error 1 : No qualifying bean of type ‘com. PJH. Service. Imp. ServiceImp’ available
error : The Exception in the thread “main” Java. Lang. ClassCastException: com. Sun. Proxy. $Proxy8 always be cast to XXX — — — — — — — dynamic proxy (proxy – target – the meaning of the class attribute)

this means roughly : no type is’ com. PJH. Service. Imp. ServiceImp “qualified bean available
H2> why?

proxy: this is caused by not configuring proxy-target-class
proxy-target-class has two values: true/false
determines whether a proxy is created based on the interface or based on the class .
if the proxy-target-class attribute value is set to true, then the class-based proxy will come into play (in which case the cglib library is required). If the proxy-target-class attribute value is set to false or this property is omitted, the standard JDK interface-based proxy will come into effect.

I use this code for:
statement : serviceImp is to implement the service interface is the parent of the
serviceImp bean1 = (serviceImp) classPathXmlApplicationContext. GetBean (serviceImp. Class);
and serviceImp is a class, not an interface
, but I did not configure proxy-target-class attribute when I was woven in, the default is proxy-target-class=false, this is based on the interface proxy, so the error is
, which is the content of the error : No type is’ com. PJH. Service. Imp. ServiceImp “qualified bean available

 <aop:config>
      <aop:pointcut id="txPointcut" expression="execution(* com.pjh.service.Imp.serviceImp.*(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
  </aop:config>

solution

solution 1:

when I change the value of the code’s proxy-target-class to true, I will not report an error, that is, I will change the class-based proxy

<aop:config proxy-target-class="true">
      <aop:pointcut id="txPointcut" expression="execution(* com.pjh.service.Imp.serviceImp.*(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
  </aop:config>

To change the passed parameters to interface, there is no need to add proxy-target-class, because the default is false, which is based on the interface proxy
declaration : serivce is the parent class of serviceImp is an interface

 service bean1 =(service) classPathXmlApplicationContext.getBean(service.class);

above is the error encountered today and its solution, if there is help, please pay attention to thumb up, this is the greatest support for bloggers, I will often update my study notes and problems encountered

Read More: