XML versus @AspectJ-style annotation for Spring AOP

When there is more than one option to choose from, it's always a dilemma, and that is the case here. Which option should you choose while using Spring AOP: XML-based or annotation-based? Each of these styles has benefits and limitations. You should consider them both before choosing the right one for your needs.

The XML style is very well-known and has been widely used since the evolution of the Spring Framework. Almost all Spring developers are handy with it. Choosing the XML style means all your configurations are in one central place. This will help to identify how many artifacts (aspects, point-cuts, and sets of advice) are defined in the system in a cleaner way. This will be a benefit in the alteration of the configuration (for example, changing the expression of a point-cut) independently.

On the other hand, with the XML style, a piece of information is split across different places. The configuration is done in XML, while the actual implementation is defined in the respective bean classes. While using @AspectJ-style annotation, there will be just a single module, Aspect, which declares that all the artifacts, such as point-cuts, advice, and so on, are well encapsulated.

There are other limitations to XML-based AOP, for example, a bean declared as an Aspect would be a singleton only. Also, you can't refer to the point-cut by its signature (name) while combining with other point-cuts. To take an example, a point-cut declaration with an annotation is as follows:

@Pointcut("execution( * com.packt.spring.aop.report.*.*(..))")
private void checkSession() {
}
@Pointcut("args(String)")
private void printUserName() {
}
@Pointcut("checkSession() && printUserName()")
private void userSession() {
}

The point-cut signatures (names) of checkSession and printUserName are used to combine them and form a new expression, userSession. The downside of XML-based configuration is that you can't combine point-cut expressions like this. 

On top of these facts, Spring AOP allows you to mix XML schema-based configuration with @AspectJ-style annotation declaration. For example, you can define a point-cut and an aspect with annotation, and declare the set of advice (interceptors) in XML-based configuration. They all can coexist without any issues.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.36