简体   繁体   中英

Spring AOP creates extra bean

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM