SPRING AOP 5252021 Spring AOP Rajkumar J 1

  • Slides: 48
Download presentation
SPRING AOP 5/25/2021 Spring AOP - Rajkumar J 1

SPRING AOP 5/25/2021 Spring AOP - Rajkumar J 1

Introduction p One of the major features available in the Spring Distribution is the

Introduction p One of the major features available in the Spring Distribution is the provision for separating the cross-cutting concerns in an Application through the means of Aspect Oriented Programming. p Aspect Oriented Programming is sensibly new and it is not a replacement for Object Oriented Programming. p In fact, AOP is another way of organizing your Program Structure. p This first section of this article looks into the various terminologies that are commonly used in the AOP Environment. p Then it moves into the support that is available in the Spring API for embedding Aspects into an Application. p 5/25/2021 Spring AOP - Rajkumar J Finally the article concludes by giving a Sample Application. 2

Introduction to AOP p The Real Problem n Since AOP is relatively new, this

Introduction to AOP p The Real Problem n Since AOP is relatively new, this section devotes time in explaining the need for Aspect Oriented Programming and the various terminologies that are used within. n Let us look into the traditional model of before explaining the various concepts. n Consider the following sample application, 5/25/2021 Spring AOP - Rajkumar J 3

Account. java p p public class Account{ n public long deposit(long deposit. Amount){ p

Account. java p p public class Account{ n public long deposit(long deposit. Amount){ p new. Amount = existing. Account + deposit. Account; p current. Amount = new. Amount; return current. Amount; n } n public long withdraw(long withdrawal. Amount){ p if (withdrawal. Amount <= current. Amount){ § current. Amount = current. Amount – withdrawal. Amount; p } n return current. Amount; n } } 5/25/2021 Spring AOP - Rajkumar J 4

n n n The above code models a simple Account Object that provides services

n n n The above code models a simple Account Object that provides services for deposit and withdrawal operation in the form of Account. deposit() and Account. withdraw() methods. Suppose say we want to add some bit of the security to the Account class, telling that only users with Bank. Admin privilege is allowed to do the operations. With this new requirement being added, let us see the modified class structure below. 5/25/2021 Spring AOP - Rajkumar J 5

Account. java p p public class Account{ n public long deposit(long deposit. Amount){ p

Account. java p p public class Account{ n public long deposit(long deposit. Amount){ p User user = get. Context(). get. User(); p if (user. get. Role(). equals("Bank. Admin"){ § new. Amount = existing. Account + deposit. Account; § current. Amount = new. Amount; p } p return current. Amount; n } n public long withdraw(long withdrawal. Amount){ p User user = get. Context(). get. User(); p if (user. get. Role(). equals("Bank. Admin"){ § if (withdrawal. Amount <= current. Amount){ § current. Amount = current. Amount – withdrawal. Amount; § } p return current. Amount; 5/25/2021 Spring AOP - Rajkumar J n } } 6

p Assume that get. Context(). get. User() someway gives the current User object who

p Assume that get. Context(). get. User() someway gives the current User object who is invoking the operation. p See the modified code mandates the use of adding additional if condition before performing the requested operation. p Assume that another requirement for the above Account class is to provide some kind of Logging and Transaction Management Facility. p Now the code expands as follows, 5/25/2021 Spring AOP - Rajkumar J 7

Account. java p public class Account{ n public long deposit(long deposit. Amount){ p logger.

Account. java p public class Account{ n public long deposit(long deposit. Amount){ p logger. info("Start of deposit method"); p Transaction trasaction = get. Context(). get. Transaction(); p transaction. begin(); p try{ § User user = get. Context(). get. User(); § if (user. get. Role(). equals("Bank. Admin"){ § new. Amount = existing. Account + deposit. Account; § current. Amount = new. Amount; p } p transaction. commit(); n }catch(Exception exception){ transaction. rollback(); } n logger. info("End of deposit method"); n return current. Amount; n } n public long withdraw(long withdrawal. Amount){ n logger. info("Start of withdraw method"); n Transaction trasaction = get. Context(). get. Transaction(); n transaction. begin(); n try{ p User user = get. Context(). get. User(); p if (user. get. Role(). equals("Bank. Admin"){ § if (withdrawal. Amount <= current. Amount){ § current. Amount = current. Amount – withdrawal. Amount; p } n transaction. commit(); 5/25/2021 Spring AOP - Rajkumar J n }catch(Exception exception){ transaction. rollback(); } n logger. info("End of withdraw method"); return current. Amount; 8

p The above code has so many dis-advantages. p The very first thing is

p The above code has so many dis-advantages. p The very first thing is that as soon as new requirements are coming it is forcing the methods and the logic to change a lot which is against the Software Design. p Remember every piece of newly added code has to undergo the Software Development Lifecycle of Development, Testing, Bug Fixing, Development, Testing, . . p This, certainly cannot be encouraged in particularly big projects where a single line of code may have multiple dependencies between other Components or other Modules in the Project. 5/25/2021 Spring AOP - Rajkumar J 9

The Solution through AOP p Let us re-visit the Class Structure and the Implementation

The Solution through AOP p Let us re-visit the Class Structure and the Implementation to reveal the facts. p The Account class provides services for depositing and withdrawing the amount. p But when you look into the implementation of these services, you can find that apart from the normal business logic, it is doing so many other stuffs like Logging, User Checking and Transaction Management. p 5/25/2021 See the pseudo-code below explains this. Springthat AOP - Rajkumar J 10

public void deposit(){ n // Transaction Management n // Logging n // Checking for

public void deposit(){ n // Transaction Management n // Logging n // Checking for the Privileged User n // Actual Deposit Logic comes here p } p public void withdraw(){ n // Transaction Management n // Logging n // Checking for the Privileged User n // Actual Withdraw Logic comes here 5/25/2021 Spring AOP - Rajkumar J p } p 11

p From the above pseudo-code, it is clear that Logging, Transaction Management and User

p From the above pseudo-code, it is clear that Logging, Transaction Management and User Checking which are never part of the Deposit or the Service functionality are made to embed in the implementation for completeness. p Specifically, AOP calls this kind of logic that cross-cuts or overlaps the existing business logic as Concerns or Cross-Cutting Concerns. p The main idea of AOP is to isolate the cross-cutting concerns from the application code thereby modularizing them as a different entity. p It doesn't mean that because the cross-cutting code has been externalized from the actual implementation, the implementation now doesn't get the required add-on functionalities. p There are ways to specify some kind of relation between the original business 5/25/2021 Spring AOP - Rajkumar J code and the Concerns through some techniques which we will see in 12 the subsequent sections.

AOP Terminologies p p It is hard to get used with the AOP terminologies

AOP Terminologies p p It is hard to get used with the AOP terminologies at first but a thorough reading of the following section along with the illustrated samples will make it easy. Let us look into the majorly used AOP jargons. Aspects n An Aspect is a functionality or a feature that cross-cuts over objects. n The addition of the functionality makes the code to Unit Test difficult because of its dependencies and the availability of the various components it is referring. n For example, in the below example, Logging and Transaction 5/25/2021 Spring AOP - Rajkumar J 13 Management are the aspects. p

p public void business. Operation(Business. Data data){ n n n 5/25/2021 // Logging logger.

p public void business. Operation(Business. Data data){ n n n 5/25/2021 // Logging logger. info("Business Method Called"); // Transaction Management Begin transaction. begin(); // Do the original business operation here transaction. end(); } Spring AOP - Rajkumar J 14

Join. Point p Join Points defines the various Execution Points where an Aspect can

Join. Point p Join Points defines the various Execution Points where an Aspect can be applied. p For example, consider the following piece of code, p public void some. Business. Operation(Business. Data data){ n //Method Start -> Possible aspect code here like logging. n try{ p // Original Business Logic here. n }catch(Exception exception){ p // Exception -> Aspect code here when some exception is raised. p } n finally{ // Finally -> Even possible to have aspect code at this point too. } n // Method End -> Aspect code here in the end of a method. } 5/25/2021 Spring AOP - Rajkumar J 15

p In the above code, we can see that it is possible to determine

p In the above code, we can see that it is possible to determine the various points in the execution of the program like Start of the Method, End of the Method, the Exception Block, the Finally Block where a particular piece of Aspect can be made to execute. p Such Possible Execution Points in the Application code for embedding Aspects are called Join Points. p It is not necessary that an Aspect should be applied to all the possible Join Points. 5/25/2021 Spring AOP - Rajkumar J 16

Pointcut p As mentioned earlier, Join Points refer to the Logical Points wherein a

Pointcut p As mentioned earlier, Join Points refer to the Logical Points wherein a particular Aspect or a Set of Aspects can be applied. p A Pointcut or a Pointcut Definition will exactly tell on which Join Points the Aspects will be applied. p To make the understanding of this term clearer, consider the following piece of code, p aspect Logging. Aspect {} aspect Transaction. Management. Aspect {} p p Assume that the above two declarations declare something of type Aspect. Now consider the following piece of. Spring code, 5/25/2021 AOP - Rajkumar J 17

p public void some. Method(){ n n //Method Start try{ p n // Some

p public void some. Method(){ n n //Method Start try{ p n // Some Business Logic Code. }catch(Exception exception){ p // Exception handler Code } n finally{ n // Finally Handler Code for cleaning resources. n } n // Method End 5/25/2021 Spring AOP - Rajkumar J n } n 18

p p In the above sample code, the possible execution points, i. e. Join

p p In the above sample code, the possible execution points, i. e. Join Points, are the start of the method, end of the method, exception block and the finally block. These are the possible points wherein any of the aspects, Logging Aspect or Transaction Management Aspect can be applied. Now consider the following Point Cut definition, pointcut method_start_end_pointcut(){ n n n p // This point cut applies the aspects, logging and transaction, before the // beginning and the end of the method. } pointcut catch_and_finally_pointcut(){ n n // This point cut applies the aspects, logging and transaction, in the catch // block (whenever an exception raises) and the finally block. } As clearly defined, it is possible to define a Point Cut that binds the Aspect to Spring AOP - Rajkumar J 19 a particular Join Point or some Set of Join Points. 5/25/2021

Advice p Now that we are clear with the terms like Aspects, Point Cuts

Advice p Now that we are clear with the terms like Aspects, Point Cuts and Join Points, let us look into what actually Advice is. p To put simple, Advice is the code that implements the Aspect. In general, an Aspect defines the functionality in a more abstract manner. p But, it is this Advice that provides a Concrete code Implementation for the Aspect. p In the subsequent sections, we will cover the necessary API in the form of classes and interfaces for supporting the Aspect Oriented Programming in Spring AOP - Rajkumar J 5/25/2021 20

Creating Advices in Spring p As mentioned previously, Advice refers to the actual implementation

Creating Advices in Spring p As mentioned previously, Advice refers to the actual implementation code for an Aspect. p Other Aspect Oriented Programming Languages also provide support for Field Aspect, i. e. intercepting a field before its value gets affected. p But Spring provides support only Method Aspect. p The following are the different types of aspects available in Spring. Before Advice n After Advice n Throws Advice 5/25/2021 n Around Advice n Spring AOP - Rajkumar J 21

Before Advice p Before Advice is used to intercept before the method execution starts.

Before Advice p Before Advice is used to intercept before the method execution starts. p In AOP, Before Advice is represented in the form of org. springframework. aop. Before. Advice. p For example, a System should make security check on users before allowing them to accessing resources. p In such a case, we can have a Before Advice that contains code which implements the User Authentication Logic. p Consider the following piece of Code, 5/25/2021 Spring AOP - Rajkumar J 22

Authentication. java p p public class Authentication extends Before. Advice{ n public void before(Method

Authentication. java p p public class Authentication extends Before. Advice{ n public void before(Method method, Object[] args, Object target) throws Throwable{ p if (args[0] instanceof User){ p User user = (User)args[0]; p // Authenticate if he/she is the right user. p } n } } The above class extends Before. Advice, thereby telling that before() method will be called before the execution of the method call. Note that the java. lang. reflect. Method method object represents target method to 5/25/2021 Spring Rajkumar J arguments that are passed on to 23 the be invoked, Object[] args refers to AOP the -various method and target refers to the object which is calling the method.

System. java p p public class System{ n public void login(){ n // Apply

System. java p p public class System{ n public void login(){ n // Apply Authentication Advice here. n } n public void logout(){ n // Apply Authentication Advice here too. n } } Note that, till now we have not seen any code that will bind the Advice implementation to the actual calling method. We will see how to do that in the Samples section. 5/25/2021 Spring AOP - Rajkumar J 24

After Advice p After Advice will be useful if some logic has to be

After Advice p After Advice will be useful if some logic has to be executed before Returning the Control within a method execution. This advice is represented by the interface org. springframework. aop. After. Returning. Advice. For example, it is common in Application to Delete the Session Data and the various information pertaining to a user, after he has logged out from the Application. These are ideal candidates for After Advice. p Clean. Up. Operation. java p public class Clean. Up. Operation implements After. Returning. Advice { public void after. Returning(Object return. Value, Method method, Object[] args, Object target) throws Throwable{ // Clean up session and user information. } } p p p p p Note that, after. Returning() will be method that will be called once the method returns normal execution. 5/25/2021 Spring AOP - Rajkumar J 25 If some exception happens in the method execution the after. Returning() method will never be called.

Throws Advice p When some kind of exception happens during the execution of a

Throws Advice p When some kind of exception happens during the execution of a method, then to handle the exception properly, Throws Advice can be used through the means of org. springframework. aop. Throws. Advice. p Note that this interface is a marker interface meaning that it doesn't have any method within it. p The method signature inside the Throws Advice can take any of the following form, p public void after. Throwing(Exception ex) public void after. Throwing(Method method, Object[] args, Object target, Exception exception) p p For example, in a File Copy program, if some kind of exception happens in the mid-way then the newly created target file has to be deleted as the partial content in the file doesn't carry any sensible meaning. 5/25/2021 p Spring AOP - Rajkumar J It can be easily achieved through the means of Throws Advice. 26

Delete. File. java p public class Delete. File implements Throws. Advice{ n n n

Delete. File. java p public class Delete. File implements Throws. Advice{ n n n public void after. Throwing(Method method, Object[] args, Object target, IOException exception){ String target. File. Name = (String)args[2]; // Code to delete the target file. } p Note that the above method will be called when an Exception, that too of type IOException is thrown by the File Copy Program. 5/25/2021 Spring AOP - Rajkumar J 27

Around Advice This Advice is very different from the other types of Advice that

Around Advice This Advice is very different from the other types of Advice that we have seen before, because of the fact that, this Advice provides finer control whether the target method has to be called or not. p Considering the above advices, the return type of the method signature is always void meaning that, the Advice itself cannot change the return arguments of the method call. p But Around Advice can even change the return type, thereby returning a brand new object of other type if needed. p Consider the following code, p pubic void relate(Object o 1, Object o 2){ o 1. establish. Relation(o 2); } p Assume that we have a method that provides an Association link between two objects. p But before that, we have to we want to ensure that the type of the Objects being passed must conform to a standard, by implementing some interfaces. p We can have this arguments check in the Around Advice rather than having it in the actual method implementation. p The Around Advice is represented by 5/25/2021 Spring AOP - Rajkumar J 28 org. aopalliance. intercept. Method. Interceptor. p

Validate. Arguments. java p public class Validate. Arguments implements Method. Interceptor { n n

Validate. Arguments. java p public class Validate. Arguments implements Method. Interceptor { n n n n public Object invoke(Method. Invocation invocation) throws Throwable { Object arguments [] = invocation. get. Arguments() ; if ((arguments[0] instanceof Parent) && (arguments[1] instanceof Child) ){ Object return. Value = invocation. proceed(); return. Value; } throw new Exception ("Arguments are of wrong type"); } } In the above code, the validation happens over the arguments to check whether they implement the right interface. p It is important to make a call to Method. Invocation. proceed(), if we are happy with the arguments validation, else the target method will 5/25/2021 Spring AOP - Rajkumar J 29 never gets invoked. p

Creating Point Cuts in Spring p p p p Point Cuts define where exactly

Creating Point Cuts in Spring p p p p Point Cuts define where exactly the Advices have to be applied in various Join Points. Generally they act as Filters for the application of various Advices into the real implementation. Spring defines two types of Point Cuts namely the Static and the Dynamic Point Cuts. The following section covers only about the Static Point Cuts as Dynamic Point Cuts are rarely used. The Point Cut Interface Point Cuts in Spring are represented by org. springframework. aop. Pointcut. Let us look into the various components of this interface. Looking at the interface Spring definition will have something like 30 the 5/25/2021 AOP - Rajkumar J following,

Pointcut. java p p public interface Pointcut{ Class. Filter get. Class. Filter() Method. Matcher

Pointcut. java p p public interface Pointcut{ Class. Filter get. Class. Filter() Method. Matcher get. Method. Matcher() } p The get. Class. Filter() method returns a Class. Filter object which determines whether the class. Object argument passed to the matches() method should be considered for giving Advices. p Following is a typical implementation of the Class. Filter interface. 5/25/2021 Spring AOP - Rajkumar J 31

My. Class. Filter. java public class My. Class. Filter implements Class. Filter{ p public

My. Class. Filter. java public class My. Class. Filter implements Class. Filter{ p public boolean matches(Class class. Object){ p String class. Name = class. Object. get. Name(); p // Check whether the class objects should be advised based on their name. p if (should. Be. Adviced(class. Name) ){ p return true; } p return false; } p The next interface in consideration is the Method. Matcher which will filter whether various methods within the class should be given Advices. AOP - Rajkumar J 32 p 5/25/2021 For example, consider the. Spring following code, p

My. Method. Matcher. java class My. Method. Matcher implements Method. Matcher{ p public boolean

My. Method. Matcher. java class My. Method. Matcher implements Method. Matcher{ p public boolean matches(Method m, Class target. Class){ p String method. Name = m. get. Name(); p if (method. Name. starts. With("get")){ p return true; p } p return false; p } p public boolean is. Runtime(){ return false; } p public boolean matches(Method m, Class target, Object[] args); p // This method wont be called in our case. So, just return false; 5/25/2021 Spring AOP - Rajkumar J 33 p }} p

p p p In the above code, we have 3 methods defined inside in

p p p In the above code, we have 3 methods defined inside in Method. Matcher interface. The is. Runtime() method should return true when we want to go for Dynamic Point cut Inclusion by depending on the values of the arguments, which usually happens at run-time. In our case, we can return false, which means that matches(Method method, Class target, Object[] args) wont be called. The implementation of the 2 argument matches() method essentially says that we want only the getter methods to be advised. We have convenient concrete classes' implementation the Point Cut classes which are used to give advices to methods statically. They are Name. Match. Method Pointcut 5/25/2021 Spring AOP n Regular Expression Pointcut n - Rajkumar J 34

Name. Match. Method Pointcut p p p p Here the name of the methods

Name. Match. Method Pointcut p p p p Here the name of the methods that are too be given advices can me directly mentioned in the Configuration File. A '*' represents that all the methods in the class should be given Advice. For example consider the following class, My. Class. java public class My. Class{ public void method 1(){} public void method 2(){} public void get. Method 1() public void get. Method 2() } Suppose we wish that only the methods get. Method 1() and get. Method 2() should be given Advice by some aspect. In that case, we can have the following Configuration file that achieves this, <bean id="get. Methods. Advisor" class="org. springframework. aop. support. Name. Match. Method. Pointcut. Advisor"> <property name="mapped. Name"> <value>get*</value> </property> </bean> The Expression get* tells that all method names starting with the method name get will be given Advices. 5/25/2021 AOP - Rajkumar 35 be If we want all the methods in the. Spring My. Class to be Jadviced, then the 'value' tag should given '*' meaning all the methods in the Class.

Regular Expression Pointcut This kind is used if you want to match the name

Regular Expression Pointcut This kind is used if you want to match the name of the methods in the Class based on Regular Expression. p Spring distribution already comes with two supported flavors of Regular Expression namely Perl Regular Expression (represented by org. springframework. aop. support. Perl 5 Regexp. Method. Pointcut) and Jdk Regular Expression (represented by org. springframework. aop. support. Jdk. Regexp. Method. Pointcut). p Considering the following class, p My. Class. java p public class My. Class{ p public void method 1(){} p public void method 11(){} p public void method 2(){} p public void get. Method 1() p public void get. Method 11() 5/25/2021 Spring AOP - Rajkumar J 36 p public void get. Method 2() } p

p The Expression 'm*1' matches method 1() and method 11(), 'get. Method. ' matches

p The Expression 'm*1' matches method 1() and method 11(), 'get. Method. ' matches only get. Method 1() and get. Method 2(). p The Configuration File should be populated with the following information for gaining this kind of support. p <bean id="reg. Exp. Advisor" class="org. springframework. aop. support. Reg. Exp. Pointcut. Advisor"> n <property name="pattern"> p <value>m*1<value> n </property> </bean> p 5/25/2021 Spring AOP - Rajkumar J 37

Sample Application Let is illustrate the various types of Advices (Before Advice, After Advice,

Sample Application Let is illustrate the various types of Advices (Before Advice, After Advice, Throws Advice and Around Advice) that we saw before in this sample Application. p For this sample application let us define Adder Service which provides logic for adding two numbers. p The various classes involved in Application along with the Advices in the subsequent sections. p 6. 2) Addder. java n This is the interface definition for the Add Service. n The interface name is Adder and it has one single method called add() taking two arguments both of type int. p Adder. java p package net. javabeat. spring. aop. introduction. test; p 5/25/2021 public interface Adder { public int add(int a, int b); } Spring AOP - Rajkumar J 38 p

p p Adder. Impl. java n The implementation class for the Add Service. n

p p Adder. Impl. java n The implementation class for the Add Service. n The logic is as simple as it returns the summation of the two numbers given as arguments. n Note that, in the later section we will see how Advices get bound with this Implementation Class. Adder. Impl. java n n package net. javabeat. spring. aop. introduction. test; public class Adder. Impl implements Adder { public int add(int a, int b){ return a+b; } } 5/25/2021 Spring AOP - Rajkumar J 39

p p Before Advice Implementation n This is the Before Advice for the Adder

p p Before Advice Implementation n This is the Before Advice for the Adder Implmentation class. n This class implements the before() method in the Method. Before. Advice interface by simply outputting a message telling that this advice is called. Log. Before. Call. Advice. java n package net. javabeat. spring. aop. introduction. test; n import java. lang. reflect. Method; n import org. springframework. aop. Method. Before. Advice; n public class Log. Before. Call. Advice implements Method. Before. Advice{ n public void before(Method method, Object[] args, Object target) { n System. out. println("Before Calling the Method"); } n } 5/25/2021 Spring AOP - Rajkumar J 40

p After Advice Implementation n The After Method Call Advice implements the After. Returning.

p After Advice Implementation n The After Method Call Advice implements the After. Returning. Advice interface providing implementation for the after. Returning() method. Like the Before Advice implementation, this Advice also outputs a simple message to the console. p Log. After. Returning. Advice. java p package net. javabeat. spring. aop. introduction. test; import java. lang. reflect. Method; import org. springframework. aop. After. Returning. Advice; public class Log. After. Returning. Advice implements After. Returning. Advice{ public void after. Returning(Object return. Value, Method method, Object[] args, Object target) throws Throwable { System. out. println("After Normal Return from Method"); } } p p p p 5/25/2021 Spring AOP - Rajkumar J 41

p Throws Advice Implementation n This Advice will be called when some kind of

p Throws Advice Implementation n This Advice will be called when some kind of Exception is caught during the method invocation. We have added a simple logic to simlate the exception when the user inputs are 0 and 0. p Log. After. Throws. Advice. java p package net. javabeat. spring. aop. introduction. test; import java. lang. reflect. Method; import org. springframework. aop. Throws. Advice; public class Log. After. Throws. Advice implements Throws. Advice{ public void after. Throwing(Method method, Object[] args, Object target, Exception exception){ System. out. println("Exception is thrown on method " + method. get. Name()); } } p p p p 5/25/2021 Spring AOP - Rajkumar J 42

p Around Advice Implementation n This Advice takes the entire control during the Method

p Around Advice Implementation n This Advice takes the entire control during the Method Execution. n It decides whether the add() method should be called or not based on the user inputs. n Note that, only if the user inputs are not 0 and 0, then the add() method will be called through Method. Invocation. proceed(). p Log. Around. Advice. java n package net. javabeat. spring. aop. introduction. test; n import org. aopalliance. intercept. *; n public class Log. Around. Advice implements Method. Interceptor{ n public Object invoke(Method. Invocation method. Invocation) throws Throwable { n Object arguments[] = method. Invocation. get. Arguments(); n int number 1 = ((Integer)arguments[0]). int. Value(); n int number 2 = ((Integer)arguments[1]). int. Value(); n if (number 1 == 0 && number 2 == 0){ n throw new Exception("Dont know how to add 0 and 0!!!"); } 5/25/2021 Spring AOP - Rajkumar J 43 n return method. Invocation. proceed(); } }

p Configuration File n n n The Configuration File has 3 sections. One section

p Configuration File n n n The Configuration File has 3 sections. One section is the Advice Bean Definition Section which is the definition set for all the 4 advices which we saw before. All the advices are given identifiers like 'before. Call', 'after. Call', 'throw. Call' and 'around. Call'. Then contains the Bean Definition for the Add implementation class which is giving the identifier 'adder. Impl'. The next interesting section is how to bind these advices to the implementation code. For this, we have to depend on Proxy. Factory Bean. This Bean is used to create Proxy objects for the Add Implementation class along with the Advice implementation. Note that the property 'proxy. Interfaces' contains the Interface Name for which the proxy class has to ge generated. In our case, it is going to be the Adder interface. The 'interceptor. Names' property takes a list of Advices to be applied to the dynamically generated proxy class. We have given all the 4 advices to this property. Finally the implementation class for the Adder service is given in the 'target' property. 5/25/2021 Spring AOP - Rajkumar J 44

p aop-test. xml p <beans xmlns="http: //www. springframework. org/schema/beans" xmlns: xsi="http: //www. w 3.

p aop-test. xml p <beans xmlns="http: //www. springframework. org/schema/beans" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //www. springframework. org/schema/beans/spring-beans-2. 0. xsd"> p <!-- Advices --> p <bean id = "before. Call" class = "net. javabeat. spring. aop. introduction. test. Log. Before. Call. Advice" /> p <bean id = "after. Call" class = "net. javabeat. spring. aop. introduction. test. Log. After. Returning. Advice" /> p <bean id = "throw. Call" class = "net. javabeat. spring. aop. introduction. test. Log. After. Throws. Advice" /> p 5/25/2021 <bean id = "around. Call" class Spring = AOP - Rajkumar J "net. javabeat. spring. aop. introduction. test. Log. Around. Advice" /> 45

p <!-- Implementation Class --> <bean id = "adder. Impl" class = "net. javabeat.

p <!-- Implementation Class --> <bean id = "adder. Impl" class = "net. javabeat. spring. aop. introduction. test. Adder. Impl" /> p <!-- Proxy Implementation Class --> p <bean id = "adder" class = "org. springframework. aop. framework. Proxy. Factory. Bean"> p <property name = "proxy. Interfaces"> <value>net. javabeat. spring. aop. introduction. test. Adder</value> </property> <property name = "interceptor. Names"> p p n <list> p p n p p p <value>before. Call</value> <value>after. Call</value> <value>throw. Call</value> <value>around. Call</value> </list> </property> <property name = "target"> <ref bean = "adder. Impl"/> </property> </bean> 5/25/2021 Spring AOP - Rajkumar J </beans> 46

p p p p p Test Class Following is the test class for the

p p p p p Test Class Following is the test class for the Adder Service. The code loads the Bean Definition File by depending on the Bean. Factory class. Watch carefully in the output for the various Advices getting called. Also, we have made to activate the Simulated Exception by passing 0 and 0 as arguments to the add() method call thereby making use of the Throws Advice. Adder. Test. java package net. javabeat. spring. aop. introduction. test; import org. springframework. beans. factory. Bean. Factory; import org. springframework. beans. factory. xml. Xml. Bean. Factory; import org. springframework. core. io. *; public class Adder. Test { public static void main(String args[]){ Resource resource = new File. System. Resource(". /src/aop-test. xml"); Bean. Factory factory = new Xml. Bean. Factory(resource); Adder adder = (Adder)factory. get. Bean("adder"); int result = adder. add(10, 10); System. out. println("Result = " + result); result = adder. add(0, 0); 5/25/2021 Spring AOP System. out. println("Result = " + result); } }- Rajkumar J 47

Conclusion p This chapter provided information on how to use Spring AOP for programming

Conclusion p This chapter provided information on how to use Spring AOP for programming the Aspects in an Application. p It started with defining what Aspects are and what are problems in having the Aspects directly embedded into the Application and how to separate them using AOP. p It then looked briefly into the various AOP Terminologies like Advice, Point Cut, Join Points etc. p Then it moved on into the various support for creating Advices using Spring AOP. p Also covered in brief are the Static Point Cuts like Name Method Match and Regular Expression Point Cuts. p Finally the article concluded with a Sample Application that illustrates the usage of different 5/25/2021 Spring AOP - Rajkumar J 48 Advices.