Spring Aspect (AOP) Example with XML based Configuration

Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.) This tutorial demonstrate an example to configure an aspect with the help of XML or Schema. Please see AOP with annotation example link for the example using @AspectJ annotation. 

Following jars (over and above your existing setup) will be needed in the classpath in order to execute the examples.


Service Class

Let's create a sample service class on which an aspect will be applied.

package com.mycompany.service;
    public class MyService {
        public void doService() {
            System.out.println("my service is called");

Aspect Class

Let's create a sample aspect class.

package com.mycompany.aspect;
    public class MyAspect {        
        public void doLog(){
            System.out.println("do logging");
        public void doSysout(){
            System.out.println("do sysout");

XML Configuration File

Following is the Spring XML or Schema way of configuring the aspects. Here doLog method of MyAspect will be called before doService is executed and doSysout method will be called after doService is executed.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

  <aop:pointcut expression="execution(* com.mycompany.service.MyService.*(..))"
   id="theBeforeExecutionOfSomeMyServiceMethod" />
  <aop:aspect ref="myAspect">
   <aop:before pointcut-ref="theBeforeExecutionOfSomeMyServiceMethod"
    method="doLog" />
   <aop:after method="doSysout" pointcut-ref="theBeforeExecutionOfSomeMyServiceMethod" />
 <bean id="myAspect" class="com.mycompany.aspect.MyAspect"/>

Please see Examples of common pointcut expressions link to see examples of common pointcut expressions.

    1 comment: