Spring AOP – XML Based Application ”; Previous Next In this chapter, we will write actual AOP applications using Spring AOP Framework. Before you start writing your first example using Spring-WS framework, you have to make sure that you have set up your Spring AOP environment properly as explained in Spring Web Services – Environment Setup chapter. Now, proceed to write a simple console-ased Spring AOP Application, which will demonstrate AOP concepts. Create a Project Step 1 − Open a command console, go the C:MVN directory and execute the following mvn command. C:MVN>mvn archetype:generate -DgroupId=com.tutorialspoint -DartifactId=Student -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false Maven will start processing and will create the complete Java application project structure. [INFO] Scanning for projects… [INFO] [INFO] ——————< org.apache.maven:standalone-pom >——————- [INFO] Building Maven Stub Project (No POM) 1 [INFO] ——————————–[ pom ]——————————— [INFO] [INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] — maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom — [INFO] Generating project in Batch mode [INFO] —————————————————————————- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0 [INFO] —————————————————————————- [INFO] Parameter: basedir, Value: C:MVN [INFO] Parameter: package, Value: com.tutorialspoint [INFO] Parameter: groupId, Value: com.tutorialspoint [INFO] Parameter: artifactId, Value: Student [INFO] Parameter: packageName, Value: com.tutorialspoint [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:MVNStudent [INFO] ———————————————————————— [INFO] BUILD SUCCESS [INFO] ———————————————————————— [INFO] Total time: 13.388 s [INFO] Finished at: 2021-12-27T20:18:26+05:30 [INFO] ———————————————————————— Step 2 − Go to C:/MVN directory. You”ll see a Java application project created, named student (as specified in artifactId). Update the POM.xml to include Spring-AOP dependencies. Add MainApp.java, Student.java, and Logging.java files. POM.xml <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>Student</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>Student</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> </dependency> </dependencies> </project> Following is the content of the Logging.java file. package com.tutorialspoint; public class Logging { /** * This is the method which I would like to execute * before a selected method execution. */ public void beforeAdvice() { System.out.println(“Going to setup student profile.”); } /** * This is the method which I would like to execute * after a selected method execution. */ public void afterAdvice() { System.out.println(“Student profile has been setup.”); } /** * This is the method which I would like to execute * when any method returns. */ public void afterReturningAdvice(Object retVal){ System.out.println(“Returning:” + retVal.toString() ); } /** * This is the method which I would like to execute * if there is an exception raised. */ public void AfterThrowingAdvice(IllegalArgumentException ex) { System.out.println(“There has been an exception: ” + ex.toString()); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); student.printThrowException(); } } Step 3 − Add the configuration file Beans.xml under src > main > resources folder. <?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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:config> <aop:aspect id = “log” ref = “logging”> <aop:pointcut id = “selectAll” expression = “execution(* com.tutorialspoint.*.*(..))”/> <aop:before pointcut-ref = “selectAll” method = “beforeAdvice”/> <aop:after pointcut-ref = “selectAll” method = “afterAdvice”/> <aop:after-returning pointcut-ref = “selectAll” returning = “retVal” method = “afterReturningAdvice”/> <aop:after-throwing pointcut-ref = “selectAll” throwing = “ex” method = “AfterThrowingAdvice”/> </aop:aspect> </aop:config> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Step 4 − Open the command console, go the C:MVN directory and execute the following mvn command. C:MVN>Student> mvn package Maven will start processing and downloading the required libraries. C:MVNStudent>mvn package [INFO] Scanning for projects… [INFO] [INFO] ———————< com.tutorialspoint:Student >——————— [INFO] Building Student 1.0-SNAPSHOT [INFO] ——————————–[ jar ]——————————— [INFO] [INFO] — maven-resources-plugin:2.6:resources (default-resources) @ Student — [INFO] Using ”UTF-8” encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] [INFO] — maven-compiler-plugin:3.1:compile (default-compile) @ Student — [INFO] Nothing to compile – all classes are up to date [INFO] [INFO] — maven-resources-plugin:2.6:testResources (default-testResources) @ Student — [INFO] Using ”UTF-8” encoding to copy filtered resources. [INFO] skip non existing resourceDirectory C:MVNStudentsrctestresources [INFO] [INFO] — maven-compiler-plugin:3.1:testCompile (default-testCompile) @ Student — [INFO] Nothing to compile – all classes are up to date [INFO] [INFO] — maven-surefire-plugin:2.12.4:test (default-test) @ Student — [INFO] Surefire report directory: C:MVNStudenttargetsurefire-reports ——————————————————- T E S T S ——————————————————- Running com.tutorialspoint.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.093 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] — maven-jar-plugin:2.4:jar (default-jar) @ Student — [INFO] ———————————————————————— [INFO] BUILD SUCCESS [INFO] ———————————————————————— [INFO] Total time: 4.213 s [INFO] Finished at: 2021-12-27T20:42:00+05:30 [INFO] ———————————————————————— C:MVNStudent> Import Project in Eclipse Step 1 − Open Eclipse. Step 2 − Select File → Import → option. Step 3 − Select Maven Projects
Category: springaop
Spring AOP – Application
Spring AOP – Annotation Based Application ”; Previous Next Let us write an example which will implement advice using Annotation based configuration. For this, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class Logging { /** Following is the definition for a Pointcut to select * all the methods available. So advice will be called * for all the methods. */ @Pointcut(“execution(* com.tutorialspoint.*.*(..))”) private void selectAll(){} /** * This is the method which I would like to execute * before a selected method execution. */ @Before(“selectAll()”) public void beforeAdvice(){ System.out.println(“Going to setup student profile.”); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); } } Following is the configuration file Beans.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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Going to setup student profile. Name : Zara Going to setup student profile. Age : 11 Print Page Previous Next Advertisements ”;
Spring AOP – Around Advice
Spring AOP – Annotation Based Around Advice ”; Previous Next @Around is an advice type, which ensures that an advice can run before and after the method execution. Following is the syntax of @Around advice. Syntax @Pointcut(“execution(* com.tutorialspoint.Student.getAge(..))”) private void selectGetName(){} @Around(“selectGetAge()”) public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ System.out.println(“Around advice”); Object[] args = jp.getArgs(); if(args.length>0){ System.out.print(“Arguments passed: ” ); for (int i = 0; i < args.length; i++) { System.out.print(“arg “+(i+1)+”: “+args[i]); } } Object result = jp.proceed(args); System.out.println(“Returning ” + result); return result.toString(); } Where, @Pointcut − Mark a function as a Pointcut execution( expression ) − Expression covering methods on which advice is to be applied. @Around − Mark a function as an advice to be executed before method(s) covered by Pointcut. To understand the above-mentioned concepts related to @Around Advice, let us write an example which will implement @Around Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application − Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class Logging { /** Following is the definition for a Pointcut to select * all the methods available. So advice will be called * for all the methods. */ @Pointcut(“execution(* com.tutorialspoint.Student.getAge(..))”) private void selectGetAge(){} /** * This is the method which I would like to execute * around a selected method execution. */ @Around(“selectGetAge()”) public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{ System.out.println(“Around advice”); Object[] args = proceedingJoinPoint.getArgs(); if(args.length>0){ System.out.print(“Arguments passed: ” ); for (int i = 0; i < args.length; i++) { System.out.print(“arg “+(i+1)+”: “+args[i]); } } Object result = proceedingJoinPoint.proceed(args); System.out.println(“Returning ” + result); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getAge(); } } Following is the configuration file Beans.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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Around advice Age : 11 Returning 11 Print Page Previous Next Advertisements ”;
Spring AOP – Overview
Spring AOP – Overview ”; Previous Next One of the key components of Spring Framework is the Aspect Oriented Programming (AOP) framework. Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns. These cross-cutting concerns are conceptually separate from the application”s business logic. There are various common good examples of aspects such as logging, auditing, declarative transactions, security, caching, etc. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other, while AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others. Spring AOP module lets interceptors intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution. Print Page Previous Next Advertisements ”;
Spring AOP – Custom Annotation ”; Previous Next As per Pointcut expressions, it may be the case that they get applied to some other beans for which advice is not intended. For example, consider the following expression. execution(* com.tutorialspoint.*.getAge(..)) A new spring bean is added with getAge() method and the advice will start getting applied to it although it may not be intended. To achieve this, we can create a custom annotation and annotate the methods on which the advice is to be applied. @Before(“@annotation(com.tutorialspoint.Loggable)”) To understand the above-mentioned concepts related to @Before Advice, let us write an example which will implement @Before Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class Logging { /** * This is the method which I would like to execute * before a selected method execution. */ @Before(“@annotation(com.tutorialspoint.Loggable)”) public void beforeAdvice(){ System.out.println(“Going to setup student profile.”); } } Following is the content of the Loggable.java file − package com.tutorialspoint; public @interface Loggable { } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } @Loggable public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); } } Following is the configuration file Beans.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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Going to setup student profile. Name : Zara Age : 11 Print Page Previous Next Advertisements ”;
Spring AOP – After Advice
Spring AOP – Annotation Based After Advice ”; Previous Next @After is an advice type which ensures that an advice runs after the method execution. Following is the syntax of @After advice. Syntax @Pointcut(“execution(* com.tutorialspoint.Student.getAge(..))”) private void selectGetName(){} @After(“selectGetAge()”) public void afterAdvice(){ System.out.println(“Student profile setup completed.”); } Where, @Pointcut − Mark a function as a Pointcut execution( expression ) − Expression covering methods on which advice is to be applied. @After − Mark a function as an advice to be executed before method(s) covered by Pointcut. To understand the above-mentioned concepts related to @After Advice, let us write an example which will implement @After Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.After; @Aspect public class Logging { /** Following is the definition for a Pointcut to select * all the methods available. So advice will be called * for all the methods. */ @Pointcut(“execution(* com.tutorialspoint.Student.getAge(..))”) private void selectGetAge(){} /** * This is the method which I would like to execute * after a selected method execution. */ @After(“selectGetAge()”) public void afterAdvice(){ System.out.println(“Student profile setup completed.”); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); } } Following is the configuration file Beans.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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Name : Zara Age : 11 Student profile setup completed. The above-defined @Pointcut uses an expression to select method getAge() defined in class(es) under the package com.tutorialspoint. @After advice uses the above-defined Pointcut as a parameter. Effectively afterAdvice() method will be called before every method covered by the above Pointcut. Print Page Previous Next Advertisements ”;
Spring AOP – Annotation Based After Throwing Advice ”; Previous Next @AfterThrowing is an advice type which ensures that an advice runs if the method throws an exception. Following is the syntax of @AfterThrowing advice. Syntax @AfterThrowing(Pointcut = “execution(* com.tutorialspoint.Student.*(..))”, throwing = “error”) public void afterThrowingAdvice(JoinPoint jp, Throwable error){ System.out.println(“Method Signature: ” + jp.getSignature()); System.out.println(“Exception: “+error); } Where, @AfterThrowing − Mark a function as an advice to be executed before method(s) covered by Pointcut, if the method throws an exception. Pointcut − Provides an expression to select a function. execution( expression ) − Expression covering methods on which advice is to be applied. throwing − Name of the exception to be returned. To understand the above-mentioned concepts related to @AfterThrowing Advice, let us write an example which will implement @AfterThrowing Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class Logging { /** * This is the method which I would like to execute * after a selected method execution throws exception. */ @AfterThrowing(Pointcut = “execution(* com.tutorialspoint.Student.*(..))”, throwing = “error”) public void afterThrowingAdvice(JoinPoint jp, Throwable error){ System.out.println(“Method Signature: ” + jp.getSignature()); System.out.println(“Exception: “+error); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.printThrowException(); } } Following is the configuration file Beans.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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Exception raised Method Signature: void com.tutorialspoint.Student.printThrowException() Exception: java.lang.IllegalArgumentException Exception in thread “main” java.lang.IllegalArgumentException at com.tutorialspoint.Student.printThrowException(Student.java:25) … Print Page Previous Next Advertisements ”;
Spring AOP – Implementations
Spring AOP – Implementations ”; Previous Next Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. XML Schema Based Aspects are implemented using regular classes along with XML based configuration. To use the AOP namespace tags described in this section, you need to import the spring AOP schema, described as follows − <?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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <!– bean definition & AOP specific configuration –> </beans> Declaring an Aspect An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute as follows. <aop:config> <aop:aspect id = “myAspect” ref = “aBean”> … </aop:aspect> </aop:config> <bean id = “aBean” class = “…”> … </bean> Here “aBean” will be configured and dependency injected just like any other Spring bean as you have seen in the previous chapters. Declaring a Pointcut A Pointcut helps in determining the join points (i.e. methods) of interest to be executed with different advices. While working with XML Schema based configuration, Pointcut will be defined as follows − <aop:config> <aop:aspect id = “myAspect” ref = “aBean”> <aop:pointcut id = “businessService” expression = “execution(* com.xyz.myapp.service.*.*(..))”/> … </aop:aspect> </aop:config> <bean id = “aBean” class = “…”> … </bean> The following example defines a Pointcut named ”businessService” that will match the execution of getName() method available in Student class under the package com.tutorialspoint. <aop:config> <aop:aspect id = “myAspect” ref = “aBean”> <aop:pointcut id = “businessService” expression = “execution(* com.tutorialspoint.Student.getName(..))”/> … </aop:aspect> </aop:config> <bean id = “aBean” class = “…”> … </bean> Declaring Advices You can declare any of the five advices inside an <aop:aspect> using the <aop:{ADVICE NAME}> element as follows. <aop:config> <aop:aspect id = “myAspect” ref = “aBean”> <aop:pointcut id = “businessService” expression = “execution(* com.xyz.myapp.service.*.*(..))”/> <!– a before advice definition –> <aop:before pointcut-ref = “businessService” method = “doRequiredTask”/> <!– an after advice definition –> <aop:after pointcut-ref = “businessService” method = “doRequiredTask”/> <!– an after-returning advice definition –> <!–The doRequiredTask method must have parameter named retVal –> <aop:after-returning pointcut-ref = “businessService” returning = “retVal” method = “doRequiredTask”/> <!– an after-throwing advice definition –> <!–The doRequiredTask method must have parameter named ex –> <aop:after-throwing pointcut-ref = “businessService” throwing = “ex” method = “doRequiredTask”/> <!– an around advice definition –> <aop:around pointcut-ref = “businessService” method = “doRequiredTask”/> … </aop:aspect> </aop:config> <bean id = “aBean” class = “…”> … </bean> You can use same doRequiredTask or different methods for different advices. These methods will be defined as a part of aspect module. @AspectJ based @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. The @AspectJ support is enabled by including the following element inside your XML Schema-based configuration file. <aop:aspectj-autoproxy/> Declaring an Aspect Aspects classes are like any other normal bean and may have methods and fields just like any other class, except that they will be annotated with @Aspect as follows. package org.xyz; import org.aspectj.lang.annotation.Aspect; @Aspect public class AspectModule { } They will be configured in XML like any other bean as follows. <bean id = “myAspect” class = “org.xyz.AspectModule”> <!– configure properties of aspect here as normal –> </bean> Declaring a Pointcut A Pointcut helps in determining the join points (i.e. methods) of interest to be executed with different advices. While working with @AspectJ based configuration, Pointcut declaration has two parts − A Pointcut expression that determines exactly which method executions we are interested in. A Pointcut signature comprising a name and any number of parameters. The actual body of the method is irrelevant and in fact should be empty. The following example defines a Pointcut named ”businessService” that will match the execution of every method available in the classes under the package com.xyz.myapp.service. import org.aspectj.lang.annotation.Pointcut; @Pointcut(“execution(* com.xyz.myapp.service.*.*(..))”) // expression private void businessService() {} // signature The following example defines a Pointcut named ”getname” that will match the execution of getName() method available in Student class under the package com.tutorialspoint. import org.aspectj.lang.annotation.Pointcut; @Pointcut(“execution(* com.tutorialspoint.Student.getName(..))”) private void getname() {} Declaring Advices You can declare any of the five advices using @{ADVICE-NAME} annotations as given below. This assumes that you already have defined a Pointcut signature method businessService(). @Before(“businessService()”) public void doBeforeTask(){ … } @After(“businessService()”) public void doAfterTask(){ … } @AfterReturning(Pointcut = “businessService()”, returning = “retVal”) public void doAfterReturnningTask(Object retVal){ // you can intercept retVal here. … } @AfterThrowing(Pointcut = “businessService()”, throwing = “ex”) public void doAfterThrowingTask(Exception ex){ // you can intercept thrown exception here. … } @Around(“businessService()”) public void doAroundTask(){ … } You can define Pointcut inline for any of the advices. Following is an example to define inline Pointcut for before advice. @Before(“execution(* com.xyz.myapp.service.*.*(..))”) public doBeforeTask(){ … } Print Page Previous Next Advertisements ”;