有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

SpringAOP中代理的java使用

我正在读一本书,其中谈到在SpringAOP中启用AspectJ支持

以下是摘自该书的一段:

To enable AspectJ annotation support in the Spring IoC container, you only have to define an empty XML element aop:aspectj-autoproxy in your bean configuration file. Then, Spring will automatically create proxies for any of your beans that are matched by your AspectJ aspects.

For cases in which interfaces are not available or not used in an application’s design, it’s possible to create proxies by relying on CGLIB. To enable CGLIB, you need to set the attribute proxy-target-class=true in <aop:aspectj-autoproxy />.


我看不懂第二段。“接口不可用”是什么意思。有人能举例说明这一点吗


共 (4) 个答案

  1. # 1 楼答案

    SpringAOP使用JDK动态代理或CGLIB为目标对象创建代理

    根据Spring文档,如果您的目标实现了至少一个接口,那么将使用JDK动态代理。但是,如果目标对象未实现任何接口,则将创建CGLIB代理

    这就是如何强制创建CGLIB代理(设置代理目标类=“true”):

     <aop:config proxy-target-class="true">
        <!-- other beans defined here... -->
     </aop:config>
    

    使用AspectJ及其autopoxy支持时,还可以强制使用CGLIB代理。这是使用<aop:aspectj-autoproxy>的地方,这里的“代理目标类”必须设置为true

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

    有关更多详细信息,请参阅Aspect Oriented Programming with Spring文档的代理机制部分

  2. # 2 楼答案

    Spring更喜欢为AOP使用接口,因为它可以使用JDKproxies

    例如,假设我有一个接口MyService

    public interface MyService {
        void doSomething();
    }
    

    和一个实现MyServiceImpl

    @Service
    public class MyServiceImpl implements MyService {
        public void doSomething() {
            // does something!
        }
    }
    

    如果Spring发现您已经为MyService配置了方面,它将创建一个实现MyService的JDK代理,然后代理所有对MyServiceImplbean的调用,在适当的地方添加方面功能

    JDK代理通过实现与目标对象相同的接口并将调用委派给它来工作;如果没有要实现的接口,它们就不起作用。如果没有上述接口,Spring需要使用一个字节码库(如CGLIB)在运行时动态创建包含方面功能的类

  3. # 3 楼答案

    Spring AOP广泛使用代理作为一种机制,以非侵入方式实现横切关注点(也称为方面),其基本思想是将代理用作包装器,以丰富原始行为,即添加事务功能

    要实现这一点,有两个选项,具体取决于原始对象是否实现了接口

    在第一种情况下(原始对象实现至少一个接口),反射API的动态代理功能用于创建代理对象,该代理对象实现与原始对象相同的接口,因此可以使用代理

    在第二种情况下(原始对象没有实现任何接口),因此必须使用更详细的技巧,这就是CGLIB出现的时候。根据项目页面“CGLIB用于扩展Java类并在运行时实现接口”。因此,在这种情况下,技巧在于创建一个代理,该代理扩展原始对象,因此可以使用

  4. # 4 楼答案

    我发现了一个博客here,它清楚地解释了AOP、缓存和;事务使用运行时代理类工作

    当不向接口编码时(引用博客的“一节,如果bean类没有实现任何接口怎么办?”):-

    By default, if your bean does not implement an interface, Spring uses technical inheritance: at startup time, a new class is created. It inherits from your bean class and adds behavior in the child methods. In order to generate such proxies, Spring uses a third party library called cglib.