Introducer aspect in spring

元气小坏坏 提交于 2020-01-06 14:09:22

问题


I am trying to inject behaviour to my bean through the 'Introduction' aspect - but unsuccessful so far.
Any help is appreciated.

The behaviour to 'introduce':

public interface MinCalculator{
    public double min(double a,double b);
}

public class MinCalculatorImpl implements MinCalculator{
    public double min(double a,double b){
        double result=(a<b)?a:b;
        return result;
    }

}

The implementation class:

public class MathsImpl{

    public void run(){ System.out.println(" This is me ");}

    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/beans-intro.xml");
        MathsImpl test = (MathsImpl) context.getBean("MathBean");
        test.run();
        MinCalculator minI=(MinCalculator)test;
        minI.min(4,2);
    }

}

The 'introducing' aspect:

@Aspect
public class IntroducerAspect {
    @DeclareParents(
    value="com.aspect.MathsImpl",
    defaultImpl=MinCalculatorImpl.class)
    public MinCalculator minCalculator;
}

THe config:

<aop:aspectj-autoproxy />
    <bean id="MathBean" class="com.aspect.MathsImpl" />
    <!-- Aspect -->
    <bean id="introAspect" class="com.aspect.IntroducerAspect" />

The result:

INFO: Loading XML bean definitions from class path resource [META-INF/beans-intr
o.xml]
Jul 30, 2013 10:46:32 PM org.springframework.beans.factory.support.DefaultListab
leBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.
DefaultListableBeanFactory@1d9fd51: defining beans [org.springframework.aop.conf
ig.internalAutoProxyCreator,MathBean,introAspect]; root of factory hierarchy
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy5 c
annot be cast to com.aspect.MathsImpl
        at com.aspect.MathsImpl.main(MathsImpl.java:13)

回答1:


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



来源:https://stackoverflow.com/questions/17953572/introducer-aspect-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!