Friday, August 10, 2012

Spring - Coding - Intercept a method call using AOP concept

Environment:
1. JDK 1.6
2. Spring 3.1
3. Log4j 1.2.16

Steps:
1. Create a main class which will implement a interface
2. Create a method interceptor/advice class which will intercept the method of class defined in step-01 
3. Setup 'Application Context' configuration with main bean and the bean which will intercept the method call

Application Context:



xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 
 
  RongBorno
 
 
 
  
 
      
 
      class="org.springframework.aop.framework.ProxyFactoryBean">
   
     
        com.spring.interceptcall.MainClassInterface
     
   
   
     
        advice
     
   
   
 


Interface and class of callee class:

package com.spring.interceptcall;
public interface MainClassInterface {
public void aMethod();
}


package com.spring.interceptcall;

public class MainClass implements MainClassInterface {
private String name;

public MainClass(String name){
this.setName(name);
}

public void aMethod(){
//Do something
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Method Interceptor/advice class:

package com.spring.interceptcall;

import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;

public class AdviceClass implements MethodBeforeAdvice {

@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
MainClass mc = (MainClass) target;

Logger log = Logger.getLogger(target.getClass());
log.debug("Class Message= "+ mc.getName() + ", method= "+ method.getName());
}
}

Class to test the sample code:

package com.spring.interceptcall;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ExecuteClass {

/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("MainClass.xml");

Logger.getLogger(ExecuteClass.class).debug("Before calling method");
((MainClassInterface)context.getBean("mainClass")).aMethod();
Logger.getLogger(ExecuteClass.class).debug("After calling method");
}

}

Log4j configuration:

### direct messages to file ###
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %5p %c{3}:%-4L - %m%n
log4j.appender.file.File=test.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, file
log4j.logger.com.spring.interceptcall=debug









No comments: