2013-07-30 48 views
0

我试图通过“介绍”方面向我的bean注入行为 - 但迄今为止尚未成功。
任何帮助表示赞赏。春季介绍人方面

行为为 '介绍':

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; 
    } 

} 

实现类:

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); 
    } 

} 

在 '引入' 方面:

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

的配置:

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

结果:

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. 
[email protected]: 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

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

+0

这个工作!上对此的解释将不胜感激。 – IUnknown

+0

[Spring:aop-proxying](http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-proxying):使用此选项可启用CGLIB代理方法;因为默认只有接口可以被代理(看看[Java:Proxy](http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html)。 使用CGLIB你也可以代理类,不仅接口(检查'测试'类型,它应该像$$ EnhancerByCGLIB或类似而不是$代理) –