0
votes

I have the following class which doesn't implement any interface :

public class HelloWorld {
...
}

the following is my xml configuration :

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <context:annotation-config/>
    <aop:aspectj-autoproxy />

    <bean id="helloBean" name="helloBean" class="com.mkyong.core.HelloWorld" autowire="byName">
        <property name="name" value="Mkyong"/>
    </bean>

    <bean id="log" class="com.mkyong.core.Log" />

    <bean id="cachedService" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="helloBean"/>
        <property name="proxyTargetClass" value="true"/>

    </bean>

The following is working and use CGLIB proxy :

HelloWorld obj = (HelloWorld) context.getBean("cachedService");

when I add the following configuration in XML it doesn't work :

   <aop:config >
        <aop:aspect id = "log" ref = "log">
            <aop:pointcut id = "selectAll"
                          expression = "execution(* com.*.*.*.*(..))"/>
            <aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
            <aop:after pointcut-ref = "selectAll" method = "afterAdvice"/>
        </aop:aspect>
    </aop:config>

the exception is the following it tries to use JDK proxy : java.lang.ClassCastException: com.sun.proxy.$Proxy9 cannot be cast to com.mkyong.core.HelloWorld

I'm confused as the following work and use CGLIB proxy :

HelloWorld obj2 = (HelloWorld) context.getBean("helloBean");

the default to use CGLIB proxy if no interface so why it's not working ?

helloBean working, cachedService not working


Update:

This fix the issue :

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

proxy-target-class="true" is needed on aop even the class doesn't implement interface which should use CGLIB proxy ,

but why it's needed ?

1

1 Answers

0
votes

I think you need to use:

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

So that AspectJ knows to use CGLIB. I am not sure whether you need to put your bean dependencies inside the aop:aspect-autoproxy element... Section 11.6 of the Spring documentation covers this: https://docs.spring.io/spring/docs/4.3.15.RELEASE/spring-framework-reference/html/aop.html