JOBS4TIMES jobs4timesLogo

Spring FrameWork

Agenda :
  1. Introduction to Spring Framework

Terminology :
  1. Concern
  2. Joinpoint
  3. Advice
  4. Pointcut
  5. Aspect
  6. Weaving
Spring AOP
Spring Advice API
  • Before advice
  • After returning advice
  • Throws advice
  • Around advice

Before Advice

public void before(Method m,)
Working with before advice :
AccountServices.java
package com.aop;

public interface AccountServices {
 boolean deposit(int accno,double amt) throws MyException;
 boolean withdraw(int accno,double amt) throws MyException;

} 
AccountServicesImpl.java
package com.aop;

public class AccountServicesImpl implements AccountServices {
	
private AccountDAO accountDAO;
	
public AccountServicesImpl(){ }

public AccountServicesImpl(AccountDAO accountDAO){
 this.accountDAO=accountDAO;
}

public boolean deposit(int accno, double amt) throws MyException {
 System.out.println("in deposit method");
 double bal=accountDAO.getBalance(accno);
 bal+=amt;
 accountDAO.setBalance(accno,bal);
 return true;
}

public boolean withdraw(int accno, double amt) throws MyException {
 System.out.println("in withdraw method");
 double bal=accountDAO.getBalance(accno);
 bal-=amt;
 
 if(bal>=1000){
	 accountDAO.setBalance(accno,bal);
	 return true;
 }
 return false;
}

}
MyException.java
package com.aop;

public class MyException extends Exception {
	
 public MyException(){ }
 
 public MyException(String message){
  super(message);
 }

} 
AccountDAO.java
package com.aop;

public interface AccountDAO {

 double getBalance(int accno)throws MyException;
 void setBalance(int accno,double amt)throws MyException; 

} 
AccountDAOTestImpl.java
package com.aop;

public class AccountDAOTestImpl implements AccountDAO {

 public double getBalance(int accno)throws MyException {
  return 5000;
 }

 public void setBalance(int accno, double amt)throws MyException {
		
 }

}
LoggingAdvice.java
package com.aop;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;

public class LoggingAdvice implements MethodBeforeAdvice {

 public void before(Method m, Object[] args, Object target){
  System.out.println("Logging Advice applied for :"+m.getName());
  Logger logger=Logger.getLogger(target.getClass());
  logger.info("Method :"+m.getName()+"invoked with"+
                               args.length+"arguments");
 }//before

}
log4j.properties
log4j.rootLogger=info, myapp
#log4j.appender.myapp=org.apache.log4j.ConsoleAppender

log4j.appender.myapp=org.apache.log4j.FileAppender
log4j.appender.myapp.file=mylog.html
log4j.appender.myapp.layout=org.apache.log4j.HTMLLayout
log4j.appender.myapp.append=false
mybeans.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-3.0.xsd">
  
<bean id="accDAO" class="com.aop.AccountDAOTestImpl"/>

<bean id="accServices" class="com.aop.AccountServicesImpl">
 <constructor-arg>
  <ref local="accDAO"/>
 </constructor-arg>
</bean>

<bean id="logging" class="com.aop.LoggingAdvice"/>
<bean id="accountServices" 
     class="org.springframework.aop.framework.ProxyFactoryBean">
 <property name="targetName">
  <value>accServices</value>
 </property>
 <property name="proxyInterfaces">
  <list>
   <value>com.aop.AccountServices</value>
  </list>
 </property>
 <property name="interceptorNames">
  <list>
   <value>logging</value>
  </list>
 </property>
</bean>
  
</beans>
AccountServicesTestCase.java
package com.aop;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class AccountServicesTestCase {
	
public static void main(String args[])throws Exception{
 BeanFactory beans=
   new XmlBeanFactory(new FileSystemResource("src/mybeans.xml"));
 AccountServices as=(AccountServices)beans.getBean("accountServices");
 System.out.println(as.withdraw(1, 1000));
 System.out.println("\n");
 System.out.println(as.deposit(1, 1000));
}
} 
result :
Logging Advice applied for : withdraw
in withdraw method
true

Logging Advice applied for : deposit
in deposit method
true

After Returning Advice

Working with AfterReturningAdvice :
MyBusinessObject.java
package com.aop;

public class MyBusinessObject{
 public String businessService(int id)throws MyException{
  System.out.println("in business service");
  if(id==0){
   System.out.println("returning test1...");
   return "Test1";
  }
  else if(id==1){
   System.out.println("returning test2...");
   return "Test2";
  }
  else {
	System.out.println("returning Hello...");
	return "Hello from business service";
  }
 }
}
MyAfterReturningAdvice.java
package com.aop;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class MyAfterReturningAdvice implements AfterReturningAdvice{

 public void afterReturning(Object return_value, Method m, 
		         Object[] args,Object target)throws Throwable {
  System.out.println("In MyAfterReturningAdvice :"+m.getName());
  System.out.println("Accessing return value...");
  if(return_value.equals("Test1")){
   System.out.println("return value found Test1");
   System.out.println("advice throwing MyException");
   throw new MyException("MyException from AfterReturningAdvice");
  }
  if(return_value.equals("Test2")){
   System.out.println("return value found Test2");
   System.out.println("advice throwing MyException");
   throw new MyException("MyException from AfterReturningAdvice");
  }
  System.out.println("return value found :"+return_value);
  System.out.println("advice ending without throwing exception...");
 }//afterReturning

}//class
MyException.java
package com.aop;

public class MyException extends Exception {
	
 public MyException(){ }
 
 public MyException(String message){
  super(message);
 }

} 
MyBusinessObjectTestCase.java
package com.aop;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class MyBusinessObjectTestCase {

 public static void main(String[] args)throws Exception{
  BeanFactory beans=
	  new XmlBeanFactory(new FileSystemResource("src/mybeans.xml"));
  MyBusinessObject bo=(MyBusinessObject)beans.getBean("myServices");
  System.out.println("Testing normal flow ...");
  System.out.println(bo.businessService(2));
  System.out.println("\n");
  
  try{
   System.out.println("Testing flow when MyException is thrown by advice");
   System.out.println(bo.businessService(0));
  }
  catch (MyException e) {
   System.out.println(e);
  }
  System.out.println("\n");
  try{
   System.out.println("Testing flow when MyException is thrown by advice");
   System.out.println(bo.businessService(1));
  }
  catch (Exception e) {
   System.out.println(e);
  }
  
 }//main
}//class
mybeans.xml
<beans>

<bean id="myser" class="com.aop.MyBusinessObject"/>
  
<bean id="afterReturning" class="com.aop.MyAfterReturningAdvice"/>

<bean id="myServices" 
        class="org.springframework.aop.framework.ProxyFactoryBean">
 <property name="targetName" value="myser"/>
 <property name="interceptorNames">
  <list>
   <value>afterReturning</value>
  </list>
 </property>
</bean>

</beans>
result :
Testing normal flow ...
in business service
returning Hello...
In MyAfterReturningAdvice :businessService
Accessing return value...
return value found :Hello from business service
advice ending without throwing exception...
Hello from business service


Testing flow when MyException is thrown by advice
in business service
returning test1...
In MyAfterReturningAdvice :businessService
Accessing return value...
return value found Test1
advice throwing MyException
com.aop.MyException: MyException from AfterReturningAdvice


Testing flow when MyException is thrown by advice
in business service
returning test2...
In MyAfterReturningAdvice :businessService
Accessing return value...
return value found Test2
advice throwing MyException
com.aop.MyException: MyException from AfterReturningAdvice

THROWS ADVICE

Working with throws advice :
MyBusinessObject.java
package com.aop;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class MyBusinessObjectTestCase {

 public static void main(String[] args)throws Exception{
  BeanFactory beans=
	  new XmlBeanFactory(new FileSystemResource("src/mybeans.xml"));
  MyBusinessObject bo=(MyBusinessObject)beans.getBean("myServices");
  
  try{
   System.out.println("Testing flow when MyException1 is
                        thrown by businessService()...");
   bo.businessService(0);
  }
  catch (MyException1 e){
   System.out.println(e);
  }
  
  System.out.println("\n");
  
  try{
   System.out.println("Testing flow when MyException2
               is thrown by businessService()...");
   bo.businessService(1);
  }
  catch (Exception e) {
   System.out.println(e);
  }  
  
  System.out.println("\n");
  System.out.println("Testing flow when there is
         no MyException thrown by businessService()...");
  bo.businessService(2);
 }//main
}//class
MyException1.java
package com.aop;

public class MyException1 extends Exception {

 public MyException1(){ }
	
 public MyException1(String message){
  super(message);
 }

}
MyException2.java
package com.aop;

public class MyException2 extends Exception {

 public MyException2(){ }
	
 public MyException2(String message){
  super(message);
 }

}
MyThrowsAdvice.java
package com.aop;

import org.springframework.aop.ThrowsAdvice;

public class MyThrowsAdvice implements ThrowsAdvice{
	
 public void afterThrowing(MyException1 me)throws Throwable{
 //Exception handling logic as per our system requirement test logic 
  System.out.println("In afterThrowing(MyException1)");
 }
	
 public void afterThrowing(MyException2 me)throws Throwable{
 //Exception handling logic as per our system requirement test logic 
  System.out.println("In afterThrowing(MyException2)");
 }
 
}
mybeans.xml
<beans>

<bean id="myser" class="com.aop.MyBusinessObject"/>
  
<bean id="exceptionHandler" class="com.aop.MyThrowsAdvice"/>

<bean id="myServices" 
     class="org.springframework.aop.framework.ProxyFactoryBean">
 <property name="targetName" value="myser"/>
 <property name="interceptorNames">
  <list>
   <value>exceptionHandler</value>
  </list>
 </property>
</bean>

</beans>
MyBusinessObjectTestCase.java
package com.aop;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class MyBusinessObjectTestCase {

 public static void main(String[] args)throws Exception{
  BeanFactory beans=
	  new XmlBeanFactory(new FileSystemResource("src/mybeans.xml"));
  MyBusinessObject bo=(MyBusinessObject)beans.getBean("myServices");
  
  try{
   System.out.println("Testing flow when MyException1 is 
                thrown by businessService()...");
   bo.businessService(0);
  }
  catch (MyException1 e){
   System.out.println(e);
  }
  
  System.out.println("\n");
  
  try{
   System.out.println("Testing flow when MyException2 is
                         thrown by businessService()...");
   bo.businessService(1);
  }
  catch (Exception e) {
   System.out.println(e);
  }  
  
  System.out.println("\n");
  System.out.println("Testing flow when there is 
        no MyException thrown by businessService()...");
  bo.businessService(2);
 }//main
}//class
output :
Testing flow when MyException1 is thrown by businessService()...
in business service
throwing MyException1...
In afterThrowing(MyException1)
com.aop.MyException1: MyException1 from MyBusinessObject

Testing flow when MyException2 is thrown by businessService()...
in business service
throwing MyException2...
In afterThrowing(MyException2)
com.aop.MyException2: MyException2 from MyBusinessObject

Testing flow when there is no MyException thrown by businessService()...
in business service
ending without throwing any exception

AROUND ADVICE

Working with around advice :
MyBusinessObject.java
package com.aop;

public class MyBusinessObject{
 public String businessService(int id)throws MyException1, MyException2{
  System.out.println("in business service");
  
  if(id==0){
   System.out.println("throwing MyException1...");
   throw new MyException1("MyException1 from MyBusinessObject");
  }
  else if(id==1){
   System.out.println("throwing MyException2...");
   throw new MyException2("MyException2 from MyBusinessObject");
  }
  else if(id==2){
   System.out.println("returning Test1...");
   return "Test1";
  }
  else{
   System.out.println("returning Test2...");
   return "Test2";
  } 
  
 }//businessService
}

MyAroundAdvice.java
package com.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyAroundAdvice implements MethodInterceptor {

 public Object invoke(MethodInvocation mi) throws Throwable {
  //all the pre processing (before advice)
 try{
  System.out.println("invoke() method before calling proceed()");
  Object o= mi.proceed();
	
  if(o.equals("Test1")){
   System.out.println("invoke() after executing proceed()");
   return "Method returned Test1 but advice has changed";
  }
   return o;	
 }//try
 catch (MyException1 e) {
  System.out.println("invoke(), proceed() thrown MyException1");
  return "Hello, there was an Exception";
 }
		
 }//invoke

}
MyException1.java
package com.aop;

public class MyException1 extends Exception {

 public MyException1(){ }
	
 public MyException1(String message){
  super(message);
 }

}
MyException2.java
package com.aop;

public class MyException2 extends Exception {

 public MyException2(){ }
	
 public MyException2(String message){
  super(message);
 }

}
log4j.properties
log4j.rootLogger=info, myapp
#log4j.appender.myapp=org.apache.log4j.ConsoleAppender

log4j.appender.myapp=org.apache.log4j.FileAppender
log4j.appender.myapp.file=mylog.html
log4j.appender.myapp.layout=org.apache.log4j.HTMLLayout
log4j.appender.myapp.append=false
mybeans.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-3.0.xsd">

<bean id="myser" class="com.aop.MyBusinessObject"/>
  
<bean id="around" class="com.aop.MyAroundAdvice"/>

<bean id="myServices" 
   class="org.springframework.aop.framework.ProxyFactoryBean">
 <property name="targetName" value="myser"/>
 <property name="interceptorNames">
  <list>
   <value>around</value>
  </list>
 </property>
</bean>

</beans>
MyBusinessObjectTestCase.java
package com.aop;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class MyBusinessObjectTestCase {

 public static void main(String[] args)throws Exception{
  BeanFactory beans=
	  new XmlBeanFactory(new FileSystemResource("src/mybeans.xml"));
  MyBusinessObject bo=(MyBusinessObject)beans.getBean("myServices");
  
  System.out.println("Testing flow when MyException1 is" +
  		               " thrown by businessService()...");
  System.out.println(bo.businessService(0)); 
  System.out.println("\n");
  try{
   System.out.println("Testing flow when MyException2 is" +
   		               " thrown by businessService()...");
   System.out.println(bo.businessService(1));
  }
  catch (MyException2 e){
   System.out.println(e);
  }
  
  System.out.println("\n");
  System.out.println("Testing flow when businessService() returns Test1...");
  System.out.println(bo.businessService(2));
  
  System.out.println("\n");
  System.out.println("Testing flow when businessService() returns Test2...");
  System.out.println(bo.businessService(3));
 }//main
}//class
output :
Testing flow when MyException1 is thrown by businessService()...
invoke() method before calling proceed()
in business service
throwing MyException1...
invoke(), proceed() thrown MyException1
Hello, there was an Exception


Testing flow when MyException2 is thrown by businessService()...
invoke() method before calling proceed()
in business service
throwing MyException2...
com.aop.MyException2: MyException2 from MyBusinessObject


Testing flow when businessService() returns Test1...
invoke() method before calling proceed()
in business service
returning Test1...
invoke() after executing proceed()
Method returned Test1 but advice has changed


Testing flow when businessService() returns Test2...
invoke() method before calling proceed()
in business service
returning Test2...
Test2

BACK