Spring AOP 创建额外的 bean [英] Spring AOP creates extra bean

查看:35
本文介绍了Spring AOP 创建额外的 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 Spring AOP.

I 'm playing with Spring AOP.

这是一个简单的类

public class CModel extends Car {
    private double torqueMeasure = 1;

    public CModel() {
        System.out.println(" C-Model constructor");        
    }
}

而Spring的配置是这样的

And Spring configuration is like this

<aop:config>
    <aop:aspect ref="audit">
        <aop:before pointcut="execution(* com.test.main..*(..))" method="firstControl"/>
            ...
    </aop:aspect>
</aop:config>

现在好了;当我添加 aop:config 并拦截 CModel 时,Spring 会调用 CModel 构造函数两次.这意味着 Spring 创建了 2 个 CModel 对象,对吗?

Ok now; when i add aop:config and intercepts CModel then Spring calls CModel constructor twice. It means Spring creates 2 CModel object, right ?

如果我删除 AOP 配置,那么 Spring 只会创建一个 CModel 对象.

If I delete AOP config then Spring creates only one CModel object.

知道为什么会这样吗?

谢谢.

推荐答案

虽然我不确定,但我的猜测是 spring 先实例化常规类,然后再做一个 CGLIB 代理,它是一个子类.注意初始化应该使用@PostConstruct,保证使用一次.

Though I'm not sure, my guess is that spring first instantiates the regular class, and then makes a CGLIB proxy, which is a subclass. Note that for initialization you should use @PostConstruct, which is guaranteed to be used once.

为了验证我的假设,在构造函数中添加一个断点并查看它何时被调用 - 有一次它应该在 CModel$EnhancedByCGLIB 之后

To verify my hypothesis, add a breakpoint in the constructor and see when it is invoked - one of the times it should be right after the CModel$EnhancedByCGLIB something

这篇关于Spring AOP 创建额外的 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆