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

查看:127
本文介绍了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天全站免登陆