Original interface is lost in Spring AOP introduction

你。 提交于 2019-12-19 10:41:53

问题


Here is my Spring AOP configuration.

<bean id="myObject" class="com.madzone.learn.spring.aop.OriginalClass"></bean>
<bean id="aspect" class="com.madzone.learn.spring.aop.AspectClass"></bean>
<aop:config>
    <aop:aspect ref="aspect">
        <aop:declare-parents
            types-matching="com.madzone.learn.spring.aop.OriginalClass+"
            implement-interface="com.madzone.learn.spring.aop.IntroducedInterface"
            default-impl="com.madzone.learn.spring.aop.IntroducedInterfaceImpl" />
    </aop:aspect>

ApplicationContext context = new ClassPathXmlApplicationContext("myApp.xml");
Object myObject = context.getBean("myObject");
if (myObject instanceof OriginalClass) {
    System.out.println("This is OriginalClass");
}
if(myObject instanceof IntroducedInterface) {
    System.out.println("This is IntroducedInterface");
}

With this introduction I was able to call the methods in the IntroducedInterface. But, I was not able to access the OriginalClass' methods. In the code snippet above, I never got the 'This is OriginalClass' printed out.

From the definition of 'Introduction' I understood that the proxy that implements the new interface will extend from OriginalClass and make its' methods accessible too.

Am I missing something here? Can someone explain the reasons, if any?

PS: The following is a picture from Spring in Action (3rd Edition) that depicts this.


回答1:


From the definition of 'Introduction' I understood that the proxy that implements the new interface will extend from OriginalClass and make its' methods accessible too.

I'm not sure where you got that impression from. All of Spring AOP is built, by default, on JDK dynamic proxies, which only work for interfaces. It's impossible to proxy a concrete class. There is support in Spring for using CGLIB proxies in order to proxy classes instead, but its use is discouraged by the reference guide in favor of programming to interfaces to reduce coupling.



来源:https://stackoverflow.com/questions/14089642/original-interface-is-lost-in-spring-aop-introduction

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