Tuesday, 9 July 2013

Spring AOP XML Schema based Example


Spring AOP Example

Aspect Oriented Programming

Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points  of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic

Important Terms

Aspect-A module which has a set of APIs providing cross-cutting requirements.

Join point- This represents a point in your application where you can plug-in AOP aspect

Advice- This is the actual action to be taken either before or after the method execution.

Point cut - This is a set of one or more join points where an advice should be executed


1. Create a class to define aspect module

package com.pretech;
public class Observer {
    * This method will execute before executing any method

    public void beforeAdvice(){
    System.out.println("Creating employee object");
    * This method will execute after executing any method

    public void afterAdvice(){
    System.out.println("Employee object created.");

2. Create a java entity class 

package com.pretech;
public class Employee {
    public Employee() {
        System.out.println("Employee constructor executed");
    private String name;
    private String company;
    public void setName(String name) { = name;
    public String getName() {
        return name;
    public String getCompany() {
        return company;
    public void setCompany(String company) { = company;


3. Create Beans configuration file (SpringConfig.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi=""
   xsi:schemaLocation=" " >

        <aop:aspect   id="observ"    ref="observer" >
            <aop:pointcut   id="aopPointCutID"    expression="execution(* com.pretech.*.*(..))" />
            <aop:before  method="beforeAdvice"    pointcut-ref="aopPointCutID" />
            <aop:after  method="afterAdvice"          pointcut-ref="aopPointCutID" />
       class="com.pretech.Employee" >
           value="Raghavan" />
           value="wipro" />
    <bean   id="observer"     class="com.pretech.Observer" />

4. Create a Test program (

package com.pretech;
import org.springframework.context.ApplicationContext;
public class AOPTest {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("SpringConfig.xml");
                Employee employee = (Employee) context.getBean("employee");

5. Output

Employee constructor executed
Employee constructor executed
Creating employee object
Employee object created.
Creating employee object
Employee object created.

Download this example

Spring AOP Example