Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of After Advice
Previous Home Next

Introduction: After advice represents those task which are to be performed after the completion of method. A Spring Framework implements After Advice are invoked from the implementation of AfterReturningAdvice interface.

Technology use to run this source code

  1. Spring 2.5 jar files
  2. Eclipse IDE
  3. Tomcat Server

Source Code:

applicationContext.xml

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="t" class="org.r4r.One"/>
<bean id="a1" class="org.r4r.BeforeAdvisor"/>
<bean id="a2" class="org.r4r.AfterAdvisor"/>
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="t"/>
<property name="interceptorNames">
<list><value>a1</value>
<value>a2</value></list>
</property>
</bean>
</beans>

Showable.java

package org.r4r;
public interface Showable {
public abstract void show();
}

One.java

package org.r4r;
public class One implements Showable {
@Override
public void show() {
System.out.println("Show() method of One invoked..");
}
}

BeforeAdvisor.java

package org.r4r;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class BeforeAdvisor implements MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("Before advice is applied..");
}
}

AfterAdvisor.java

package org.r4r;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class AfterAdvisor implements AfterReturningAdvice {
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("After advisor is provide service..");
}
}

ProxyTest.java

package org.r4r;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class ProxyTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
System.out.println("Obtaining proxy of one..");
Showable p=(Showable)f.getBean("proxy");
System.out.println("Proxy obtaining invoked.");
p.show();
}
}

output:

 Obtaining proxy of one..
Proxy obtaining invoked.
Before advice is applied..
Show() method of One invoked..
After advisor is provide service..
Previous Home Next