Spring AOP creates extra bean

折月煮酒 提交于 2019-12-07 07:37:35

问题


I 'm playing with Spring AOP.

Here is a simple class

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

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

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>

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

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

Any idea why it is like this ?

Thanks.


回答1:


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.

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




回答2:


When Spring creates a proxy to your class, it will use CGLIB to generate a class that subclasses CModel. The net affect is your constructor will be called twice.

Check out the Spring documentation for more detail (specifically the third bullet): http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-proxying

As a side note, Spring will use the JDK proxying mechanism if your class implements an interface -- and the JDK proxying mechanism will not call your constructor.



来源:https://stackoverflow.com/questions/7968248/spring-aop-creates-extra-bean

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