JaiswalTraining

Get the online training

Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven








Spring AOP Module

Introduction
  • AOP is a philosophy that is related to style of programming. It addresses issues that can be solved in other approaches, but in a more elegant way.
  • Aspect Oriented Programming is new and it is not a replacement for Object Oriented Programming. In fact, AOP is another way of organizing your Program Structure.
Why AOP?

  • Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns
  • Examples of cross-cutting concerns
    • Logging
    • Transaction management
    • Security
    • Auditing
    •  Locking
    •  Event handling
  • Complements OO programming
  • Core business concerns vs. Crosscutting enterprise concerns
  • Aspects can be added or removed as needed without changing your code
  • Aspects are coded with pure Java code. You do not need to learn pointcut query languages that are available in other AOP Implementation.
  • Spring aspects can be configured using its own IoC container.
    • Objects obtained from the IoC container can be transparently advised based on configuration
    • Spring AOP has built in aspects such as providing transaction
      management, performance monitoring and more for your beans
Other Features:-
  • Spring allows you to chain together interceptors and advice with
    precedence.
  • Spring AOP also includes advisors that contain advice and
    pointcut filtering
  • ProxyFactoryBean – sources AOP proxies from a Spring
    BeanFactory
  • IOC+AOP is a great combination that is non-invasive

Components of AOP

Aspect – unit of modularity for crosscutting concerns
Join point – well-defined points in the program flow
Pointcut – join point queries where advice executes
Advice – the block of code that runs based on the pointcut definition
Weaving – can be done at runtime or compile time. Inserts the advice
(crosscutting concerns) into the code (core concerns).

Advice
  • The job of an aspect is called advice.
  • Advice defines both the what and the when of an aspect.
  • It also describing the job that an aspect will perform, advice addresses the question of when to
    perform the job. Should it be applied before a method is invoked? After the method is invoked? Both before and after method invocation? Or should it only be applied if a method throws an exception?
 Join Point
  • It is a point in the execution of the application where an aspect can be plugged in.
  • point could be a method being called, an exception being thrown, or even a field
    being modified.
  • These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior
Point Cut
  • If advice defines the what and when of aspects then pointcuts define the where.
  • It matches one or more joinpoints at which advice should be woven.
  • Some AOP frameworks allow you to create dynamic pointcuts that determine
    whether to apply advice based on runtime decisions, such as the value of method parameters.
Aspect
  • An aspect is the merger of advice and pointcuts
  • Taken together, advice and pointcuts define everything there is to know about an aspect—what it does and where and when it does it.
Target
  • A target is the object that is being advised.
  • the target object is free to focus on its primary concern, oblivious to any advice being applied
Proxy
  • A proxy is the object created after applying advice to the target object.
  • the target object (pre-AOP) and the proxy object (post-AOP) are the same
Weaving
  • Weaving is the process of applying aspects to a target object to create a new, proxied
    object.
  • The aspects are woven into the target object at the specified joinpoints.
  • The weaving can take place at several points in the target object’s lifetime:
    • Compile time
    • Classload time
    • Runtime

Type of Advice

Supports the following advices
  • method before
  • method after returning
  • throws advice
  • around advice (uses AOPAlliance MethodInterceptor directly)




The before() method takes three parameters. The first parameter is a java.lang.reflect.Method object that represents the method to which the advice is being applied. The second parameter is an array of Objects that are the arguments that were passed to the method when the method was called. The final parameter is the target of the method invocation (i.e., the object on which the
method was called).

afterReturning() method aren’t much different than the parameters to the before() method of MethodBeforeAdvice.
The only difference is that an additional parameter has been added as the first parameter. This parameter holds the value that was returned from the invoked method.

Unlike MethodBeforeAdvice and AfterReturningAdvice, however, ThrowsAdvice doesn’t require that any method be implemented. ThrowsAdvice is only a marker interface that tells Spring that the advice may wish to handle a thrown exception.

public void afterThrowing([method], [args], [target], throwable);

All of the parameters of afterThrowing() are optional except for the one that is a Throwable type. It is this parameter that tells Spring which exceptions should be handled by the advice


Around advice is effectively before, after-returning, and after-throwing advice all rolled into one.
  • around advice is defined by the AOP Alliance’s Method-Interceptor interface.
  • Around advice also offers you the opportunity to inspect and alter the value returned from the advised method.
  • AfterReturningAdvice only allows you to inspect the returned value.



Example:-
  • In this example we have  created two interface CalculatorDAO.java and CalculatorJavaBean.java
  • Next we have created  above interfaces implemented classes CalculatorDAOImplementation.java
    and
    CalculatorJavaBeanImplementaion.java
  • Next we have created different  interceptor one by one.
  • Springconfiguration.xml file where we have configured all the classes. and provide Intercepter for ProxyFactoryBean 
  • finally we have created a Program class from where we have tested the application.

CalculatorDAO.java

package calculatorpack;

public interface CalculatorDAO 
{
  public int add(int a,int b);
  public int sub(int a,int b);
  public int div(int a,int b);
  public int mul(int a,int b);
}

CalculatorDAOImplementation.java
package calculatorpack;

public class CalculatorDAOImplementation
 
implements CalculatorDAO {
  public int add(int a, int b) {
    return a + b;
  }

  public int sub(int a, int b) {
    return a - b;
  }

  public int div(int a, int b) {
    return a / b;
  }

  public int mul(int a, int b) {
    return a * b;
  }
}

CalculatorJavaBean.java
package calculatorpack;

public interface CalculatorJavaBean 
{
  public int doAddition(int a,int b);
  public int doSubstraction(int a,int b);
  public int doDivision(int a,int b);
  public int doMultiplication(int a,int b);
}

CalculatorJavaBeanImplementation.java

package calculatorpack;

public class CalculatorJavaBeanImplementation
implements CalculatorJavaBean 
{
  CalculatorDAO calculatordao;
  
  public void setCalculatordao(CalculatorDAO calculatordao
  {
    this.calculatordao=calculatordao;
  }
  
  public int doAddition(int a,int b
  {
    System.out.println("doAddition()");
    System.out.println("{");
    System.out.println("}");
    
    return calculatordao.add(a,b);
  }
  public int doSubstraction(int a,int b
  {
    System.out.println("doSubstraction()");
    System.out.println("{");
    System.out.println("}");
    
    return calculatordao.sub(a,b);
  }
  public int doDivision(int a,int b
  {
    System.out.println("doDivision()");
    System.out.println("{");
    System.out.println("}");
    
    return calculatordao.div(a,b);
  }
  public int doMultiplication(int a,int b
  {
    System.out.println("doMultiplication()");
    System.out.println("{");
    System.out.println("}");
    
    return calculatordao.mul(a,b);
  }
}

MethodCheckBeforeAdvice.java

package calculatorpack;

import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class MethodCheckBeforeAdvice implements MethodBeforeAdvice {
  public void before(Method method, Object[] args, Object target)
      throws Throwable {
    System.out.println("MethodCheckBeforeAdvice applied for "
        + method.getName());
    System.out.println("MethodBeforeAdvice stared.....");
    System.out.println("{");
    for (int i = 1; i <= args.length; i++) {
      Object arg = (Objectargs[--i];
      i++;
      System.out.println("\tArgument Value " + i + " = " + arg);
    }
    System.out.println("\tTarget Class = " + target.getClass().getName());
    System.out.println("}");
    System.out.println("MethodBeforeAdvice ended.....");
  }
}


 Program.java
package calculatorpack;

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

public class Program {
  public static void main(String[] args) {
    try {
      BeanFactory beanfactory = new XmlBeanFactory(
          new FileSystemResource(
              "src/calculatorpack/SpringContainer.xml"));

      CalculatorJavaBean calculatorservice =
 
(CalculatorJavaBeanbeanfactory
          .getBean("calculatorservices");

      calculatorservice.doAddition(102);
      // System.out.println();
      // calculatorservice.doSubstraction(10,2);
      // System.out.println();
      // calculatorservice.doDivision(10,0);
      // System.out.println();
      // calculatorservice.doMultiplication(10,2);
    catch (Exception e) {
      System.out.println("Exception : ");
      System.out.println("----->");
      e.printStackTrace();
      System.out.println("<-----");
    }
  }
}

Springconfiguration.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="calculatordao"
class="calculatorpack.CalculatorDAOImplementation" />

  <bean id="calculatorjavabean"
class
="calculatorpack.CalculatorJavaBeanImplementation">
    <property name="calculatordao" ref="calculatordao" />
  </bean>

  <bean id="methodcheckbeforeadvice"
class="calculatorpack.MethodCheckBeforeAdvice" />
  <bean id="methodcheckafteradvice"
class
="calculatorpack.MethodCheckAfterAdvice" />
  <bean id="methodcheckthrowsadvice"
class
="calculatorpack.MethodCheckThrowsAdvice" />
  <bean id="methodcheckaroundadvice"
 
class="calculatorpack.MethodCheckAroundAdvice" />

  <bean id="calculatorservices"
 
class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="targetName"
 
value="calculatorjavabean" />
    <property name="proxyInterfaces">
      <list>
        <value>calculatorpack.CalculatorJavaBean</value>
      </list>
    </property>
    <property name="interceptorNames">
      <list>
        <value>methodcheckbeforeadvice</value>
        <!--<value>methodcheckafteradvice</value>-->
        <!--<value>methodcheckthrowsadvice</value>-->
        <!--<value>methodcheckaroundadvice</value>
      -->
      </list>
    </property>
  </bean>
</beans>



Output:-




MethodCheckAfterAdvice.java

package calculatorpack;

import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;

public class MethodCheckAfterAdvice implements AfterReturningAdvice 
{
  public void afterReturning(Object returnvalue,Method method,Object[]
 
args,Object targetthrows Throwable 
  {
    System.out.println("MethodCheckAfterAdvice applied for "+method.getName());
    System.out.println("MethodAfterAdvice stared.....");
    System.out.println("{");
    System.out.println("\tMethod Return Value = "+returnvalue);
    System.out.println("\tTarget Class = "+target.getClass().getName());
    System.out.println("}");
    System.out.println("MethodAfterAdvice ended.....");
  }
}


Output:-




MethodCheckThrowsAdvice.java

package calculatorpack;

import org.springframework.aop.ThrowsAdvice;
import java.sql.SQLException;

public class MethodCheckThrowsAdvice implements ThrowsAdvice {
  public void afterThrowing(ArithmeticException aethrows Throwable {
    System.out.println("MethodCheckThrowsAdvice applied.");
    System.out.println("MethodThrowAdvice stared.....");
    System.out.println("{");
    System.out.println("\tArithmeticException : ");
    System.out.println("\t----->");
    System.out.println("\t" + ae);
    System.out.println("\t<-----");
    System.out.println("}");
    System.out.println("MethodThrowAdvice ended.....");
  }

  public void afterThrowing(SQLException sqlethrows Throwable {
    System.out.println("MethodCheckThrowsAdvice applied.");
    System.out.println("MethodThrowAdvice stared.....");
    System.out.println("{");
    System.out.println("\tSQLException : ");
    System.out.println("\t----->");
    System.out.println("\t" + sqle);
    System.out.println("\t<-----");
    System.out.println("}");
    System.out.println("MethodThrowAdvice ended.....");
  }
}


Output:-



MethodCheckAroundAdvice.java

package calculatorpack;

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

public class MethodCheckAroundAdvice implements MethodInterceptor 
{
  public Object invoke(MethodInvocation mithrows Throwable 
  {
    System.out.println("MethodCheckAroundAdvice applied.");
    System.out.println("MethodAroundAdvice stared.....");
    System.out.println("{");
    System.out.println("\tIn invoke() before calling proceed().");
    System.out.println("\t----->");
    Object object=mi.proceed();
    System.out.println("\tIn invoke() after executing proceed().");
    System.out.println("\t<-----");
    System.out.println("}");
    System.out.println("MethodAroundAdvice ended.....");
    
    return object;
  }
}


Output:-



Download Zip Code