0
votes

I am studying for the Spring Core certification and I have the following doubt related to AOP named pointcut

So for example I can have the following code into an XML configuration file that defines pointut with no name:

<aop:config>
    <aop:aspect ref=“propertyChangeTracker”>
        <aop:before pointcut=“execution(void set*(*))” method=“trackChange”/>
    </aop:aspect>
</aop:config>

<bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” />

And this should work in the following way:

First it defines the pointcut as all the method having name that begin with set and that take a single parameter (of any type) returning void.

And it is definied the advice as the trackChange() method inside the class example.PropertyChangeTracker

So what it happens is that when a setter method is called during the application lifecycle it is automatically called the trackChange() method inside the class example.PropertyChangeTracker.

Ok, this is pretty simple.

Now instead I have this AOP XML configuration that contains named pointcuts:

<aop:config>
    <aop:pointcut id=“setterMethods” expression=“execution(void set*(*))”/>

    <aop:aspect ref=“propertyChangeTracker”>
        <aop:after-returning pointcut-ref=“setterMethods” method=“trackChange”/>
        <aop:after-throwing pointcut-ref=“setterMethods” method=“logFailure”/>
    </aop:aspect>
</aop:config>

<bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” />

As in the first configuration the pointcut remain related to some particulars setter methods (but in this case the advices are respectivelly after-returning and after-throwing.

And the definied advices are the trackChange() and the logFailure() methods definied inside the example.PropertyChangeTracker class.

Differently from the first example the 2 advices are definied a name that is represented by the value of the pointcut-ref=“setterMethods”. But what exatly means? What can be used for?

Tnx

1

1 Answers

3
votes

Long question, simple answer: You can refer to the pointcut by its name, so if you have multiple advices referring to the same pointcut you only need to change it in one place and leave the references untouched. This is similar to using a variable vs. literals in Java code.

Look at your own example: The two advices trackChange and logFailure both use the same pointcut, which is quite convenient. DRY - don't repeat yourself. ;-) Sometimes pointcuts are a bit more complex than yours, they can span multiple lines in complex scenarios.