Spring详细内容-Spring AOP En(4)

喜欢ヅ旅行 2023-09-24 19:11 223阅读 0赞

1.Spring AOP

  • Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides modularity.
  • But the key unit of modularity is aspect than class.
  • AOP breaks the program logic into distinct parts (called concerns).
  • It is used to increase modularity by cross-cutting concerns.
  • A cross-cutting concern is a concern that can affect the whole application and should be centralized in one location in code as possible, such as transaction management, authentication, logging, security etc.

1)Why use AOP?

  • It provides the pluggable way to dynamically add the additional concern before, after or around the actual logic.

2)Where use AOP?

  • AOP is mostly used in following cases:

    • to provide declarative enterprise services such as declarative transaction management.
    • It allows users to implement custom aspects.

3)AOP Concepts and Terminology

  • Join point

    • Join point is any point in your program such as method execution, exception handling, field access etc.
    • Spring supports only method execution join point.
  • Advice

    • Before Advice: it executes before a join point.
    • After Returning Advice: it executes after a joint point completes normally.
    • After Throwing Advice: it executes if method exits by throwing an exception.
    • After (finally) Advice: it executes after a join point regardless of join point exit whether normally or exceptional return.
    • Around Advice: It executes before and after a join point.
  • Pointcut

    • It is an expression language of AOP that matches join points.
  • Introduction

    • It is an expression language of AOP that matches join points.
  • Target Object

    • It is the object i.e. being advised by one or more aspects.
    • It is also known as proxied object in spring because Spring AOP is implemented using runtime proxies.
  • Aspect

    • It is a class that contains advices, joinpoints etc.
  • Interceptor

    • It is an aspect that contains only one advice.
  • AOP Proxy

    • It is used to implement aspect contracts, created by AOP framework.
    • It will be a JDK dynamic proxy or CGLIB proxy in spring framework.
  • Weaving

    • It is the process of linking aspect with other application types or objects to create an advised object.
    • Weaving can be done at compile time, load time or runtime. Spring AOP performs weaving at runtime.

4)AOP Implementations

  • AspectJ
  • Spring AOP
  • JBoss AOP

5) 3 ways to use spring AOP

  • By Spring1.2 Old style (dtd based) (also supported in Spring3)
  • By AspectJ annotation-style
  • By Spring XML configuration-style(schema based)

2.By Spring1.2 Old style (dtd based) (also supported in Spring3)

There are 4 types of advices supported in spring1.2 old style aop implementation.

  • Before Advice it is executed before the actual method call.
  • After Advice it is executed after the actual method call. If method - returns a value, it is executed after returning value.
  • Around Advice it is executed before and after the actual method call.
  • throws Advice it is executed if actual method throws exception.

Understanding the hierarchy of advice interfaces

在这里插入图片描述
MethodBeforeAdvice interface extends the BeforeAdvice interface.

AfterReturningAdvice interface extends the AfterAdvice interface.

ThrowsAdvice interface extends the AfterAdvice interface.

MethodInterceptor interface extends the Interceptor interface. It is used in around advice.

1)Before Advice

  1. public class A{
  2. public void m(){
  3. System.out.println("actual business logic");}
  4. }
  5. public class BeforeAdvisor implements MethodBeforeAdvice {
  6. @Override
  7. public void before(Method method, Object[] args, Object target) throws Throwable {
  8. System.out.println("additional concern before actual logic");
  9. }
  10. }
  11. <?xml version="1.0" encoding="UTF-8"?>
  12. <beans
  13. xmlns="http://www.springframework.org/schema/beans"
  14. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  15. xmlns:p="http://www.springframework.org/schema/p"
  16. xsi:schemaLocation="http://www.springframework.org/schema/beans
  17. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  18. <bean id="a" class="com.amy.A"></bean>
  19. <bean id="before" class="com.amy.BeforeAdvisor"></bean>
  20. <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
  21. <property name="target" ref="a"></property>
  22. <property name="interceptorNames">
  23. <list>
  24. <value>before</value>
  25. </list>
  26. </property>
  27. </bean>
  28. </beans>
  29. public class Test {
  30. public static void main(String[] args) {
  31. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  32. A a= context.getBean("proxy",A.class);
  33. a.m();
  34. }
  35. }
  36. additional concern before actual logic
  37. actual business logic

Understanding ProxyFactoryBean class:

  • The ProxyFactoryBean class is provided by Spring Famework. It contains 2 properties target and interceptorNames.
  • The instance of A class will be considered astarget objectand the instance of advisor class as interceptor.
  • You need to pass the advisor object as the list object as in the xml file given above.





    before


    public class ProxyFactoryBean{

    1. private Object target;
    2. private List interceptorNames;
    3. //getters and setters

    }

Printing additional information in MethodBeforeAdvice

  1. public class A{
  2. public void m(){
  3. System.out.println("actual business logic");}
  4. }
  5. <?xml version="1.0" encoding="UTF-8"?>
  6. <beans
  7. xmlns="http://www.springframework.org/schema/beans"
  8. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9. xmlns:p="http://www.springframework.org/schema/p"
  10. xsi:schemaLocation="http://www.springframework.org/schema/beans
  11. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  12. <bean id="a" class="com.amy.A"></bean>
  13. <bean id="before" class="com.amy.BeforeAdvisor"></bean>
  14. <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
  15. <property name="target" ref="a"></property>
  16. <property name="interceptorNames">
  17. <list>
  18. <value>before</value>
  19. </list>
  20. </property>
  21. </bean>
  22. </beans>
  23. public class BeforeAdvisor implements MethodBeforeAdvice {
  24. @Override
  25. public void before(Method method, Object[] args, Object target) throws Throwable {
  26. System.out.println("additional concern before actual logic");
  27. System.out.println("method info:" +" method.getName() is "+ method.getName() + " method.getModifiers() is " + method.getModifiers());
  28. System.out.println("argument info:");
  29. for (Object arg : args) {
  30. System.out.println("arg: "+ arg);
  31. }
  32. System.out.println("target Object:" + target);
  33. System.out.println("target object class name: " + target.getClass().getName());
  34. }
  35. }
  36. public class Test {
  37. public static void main(String[] args) {
  38. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  39. A a= context.getBean("proxy",A.class);
  40. System.out.println("proxy class name: "+a.getClass().getName());
  41. a.m();
  42. }
  43. }
  44. proxy class name: com.amy.A$$EnhancerBySpringCGLIB$$46ca4f4d
  45. additional concern before actual logic
  46. method info: method.getName() is m method.getModifiers() is 1
  47. argument info:
  48. target Object:com.amy.A@6a396c1e
  49. target object class name: com.amy.A
  50. actual business logic

2)After Advice

  1. public class A{
  2. public void m(){
  3. System.out.println("actual business logic");}
  4. }
  5. public class AfterAdvisor implements AfterReturningAdvice {
  6. @Override
  7. public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
  8. System.out.println("additional concern after returning advice");
  9. }
  10. }
  11. <?xml version="1.0" encoding="UTF-8"?>
  12. <beans
  13. xmlns="http://www.springframework.org/schema/beans"
  14. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  15. xmlns:p="http://www.springframework.org/schema/p"
  16. xsi:schemaLocation="http://www.springframework.org/schema/beans
  17. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  18. <bean id="a" class="com.amy.A"></bean>
  19. <bean id="after" class="com.amy.AfterAdvisor"></bean>
  20. <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
  21. <property name="target" ref="a"></property>
  22. <property name="interceptorNames">
  23. <list>
  24. <value>after</value>
  25. </list>
  26. </property>
  27. </bean>
  28. </beans>
  29. public class Test {
  30. public static void main(String[] args) {
  31. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  32. A a= context.getBean("proxy",A.class);
  33. a.m();
  34. }
  35. }
  36. actual business logic
  37. additional concern after returning advice

3)Around Advice

  1. public class A{
  2. public void m(){
  3. System.out.println("actual business logic");}
  4. }
  5. public class AroundAdvisor implements MethodInterceptor {
  6. @Override
  7. public Object invoke(MethodInvocation invocation) throws Throwable {
  8. Object object;
  9. System.out.println("additional concern before actual logic");
  10. object=invocation.proceed();
  11. System.out.println("additional concern after actual logic");
  12. return object;
  13. }
  14. }
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <beans
  17. xmlns="http://www.springframework.org/schema/beans"
  18. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  19. xmlns:p="http://www.springframework.org/schema/p"
  20. xsi:schemaLocation="http://www.springframework.org/schema/beans
  21. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  22. <bean id="a" class="com.amy.A"></bean>
  23. <!-- <bean id="before" class="com.amy.BeforeAdvisor"></bean>-->
  24. <!-- <bean id="after" class="com.amy.AfterAdvisor"></bean>-->
  25. <bean id="around" class="com.amy.AroundAdvisor"></bean>
  26. <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
  27. <property name="target" ref="a"></property>
  28. <property name="interceptorNames">
  29. <list>
  30. <value>around</value>
  31. </list>
  32. </property>
  33. </bean>
  34. </beans>
  35. public class Test {
  36. public static void main(String[] args) {
  37. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  38. A a= context.getBean("proxy",A.class);
  39. a.m();
  40. }
  41. }
  42. additional concern before actual logic
  43. actual business logic
  44. additional concern after actual logic

4)Throws Advice

  1. public class Validator {
  2. public void Validate(int age) throws ArithmeticException {
  3. if(age<18){
  4. throw new ArithmeticException("No Valid Age");
  5. }else{
  6. System.out.println("vote confirmed");
  7. }
  8. }
  9. }
  10. public class ThrowsAdvisor implements ThrowsAdvice {
  11. public void afterThrowing(Exception ex){
  12. System.out.println("additional concern if exception occurs");
  13. }
  14. }
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <beans
  17. xmlns="http://www.springframework.org/schema/beans"
  18. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  19. xmlns:p="http://www.springframework.org/schema/p"
  20. xsi:schemaLocation="http://www.springframework.org/schema/beans
  21. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  22. <bean id="v" class="com.amy.Validator"></bean>
  23. <!-- <bean id="before" class="com.amy.BeforeAdvisor"></bean>-->
  24. <!-- <bean id="after" class="com.amy.AfterAdvisor"></bean>-->
  25. <!-- <bean id="around" class="com.amy.AroundAdvisor"></bean>-->
  26. <bean id="throw" class="com.amy.ThrowsAdvisor"></bean>
  27. <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
  28. <property name="target" ref="v"></property>
  29. <property name="interceptorNames">
  30. <list>
  31. <value>throw</value>
  32. </list>
  33. </property>
  34. </bean>
  35. </beans>
  36. public class Test {
  37. public static void main(String[] args) {
  38. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  39. Validator v= context.getBean("proxy",Validator.class);
  40. try{
  41. v.Validate(12);
  42. }catch (Exception e){
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. additional concern if exception occurs
  48. java.lang.ArithmeticException: No Valid Age
  49. at com.amy.Validator.Validate(Validator.java:10)
  50. at com.amy.Validator$$FastClassBySpringCGLIB$$f91662a4.invoke(<generated>)
  51. at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
  52. at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
  53. at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
  54. at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
  55. at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.invoke(ThrowsAdviceInterceptor.java:113)
  56. at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  57. at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
  58. at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
  59. at com.amy.Validator$$EnhancerBySpringCGLIB$$629ab8c0.Validate(<generated>)
  60. at com.amy.Test.main(Test.java:21)
  61. Process finished with exit code 0

3.Spring AOP AspectJ Annotation

  • The Spring Framework recommends you to use Spring AspectJ AOP implementation over the Spring 1.2 old style dtd based AOP implementation because it provides you more control and it is easy to use.
  • There are two ways to use Spring AOP AspectJ implementation:

    • By annotation: We are going to learn it here.
    • By xml configuration (schema based): We will learn it in next page.

1)By annotation

  • Spring AspectJ AOP implementation provides many annotations:

    @Aspect declares the class as aspect.
    @Pointcut declares the pointcut expression.

  • The annotations used to create advices are given below:

    @Before declares the before advice. It is applied before calling the actual method.
    @After declares the after advice. It is applied after calling the actual method and before returning result.
    @AfterReturning declares the after returning advice. It is applied after calling the actual method and before returning result. But you can get the result value in the advice.
    @Around declares the around advice. It is applied before and after calling the actual method.
    @AfterThrowing declares the throws advice. It is applied if actual method throws exception.

(1)Pointcut

  • Pointcut is an expression language of Spring AOP.
  • The @Pointcut annotation is used to define the pointcut.
  • We can refer the pointcut expression by name also.

    @Pointcut(“execution( Operation.(..))”)
    private void doSomething() {

    1. }

It will be applied on all the public methods.

  1. @Pointcut("execution(public Operation.*(..))")

It will be applied on all the methods of Operation class.

  1. @Pointcut("execution(* Operation.*(..))")

It will be applied on all the public setter methods of Employee class.

  1. @Pointcut("execution(public Employee.set*(..))")

It will be applied on all the methods of Operation class that returns int value.

  1. @Pointcut("execution(int Operation.*(..))")

(2)@Before

  1. public class Operation {
  2. public void msg(){
  3. System.out.println("msg method invoked");}
  4. public int m(){
  5. System.out.println("m method invoked");return 2;}
  6. public int k(){
  7. System.out.println("k method invoked");return 3;}
  8. }
  9. package com.amy;
  10. import org.aspectj.lang.JoinPoint;
  11. import org.aspectj.lang.annotation.Aspect;
  12. import org.aspectj.lang.annotation.Before;
  13. import org.aspectj.lang.annotation.Pointcut;
  14. /**
  15. * @author: Amy
  16. * @create: 2023-02-20 15:05
  17. **/
  18. @Aspect
  19. public class TrackOperation {
  20. @Pointcut("execution(* Operation.*(..))")
  21. public void k(){
  22. }//pointcut name
  23. @Before("k()")//applying pointcut on before advice
  24. public void myadvice(JoinPoint jp){
  25. //it is advice (before advice)
  26. System.out.println("additional concern");
  27. }
  28. }
  29. <?xml version="1.0" encoding="UTF-8"?>
  30. <beans
  31. xmlns="http://www.springframework.org/schema/beans"
  32. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  33. xmlns:p="http://www.springframework.org/schema/p"
  34. xsi:schemaLocation="http://www.springframework.org/schema/beans
  35. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  36. <bean id="op" class="com.amy.Operation"></bean>
  37. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  38. <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
  39. </beans>
  40. public class Test {
  41. public static void main(String[] args) {
  42. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  43. Operation o= (Operation) context.getBean("op");
  44. System.out.println("calling msg...");
  45. o.msg();
  46. System.out.println("calling m...");
  47. o.m();
  48. System.out.println("calling k...");
  49. o.k();
  50. }
  51. }
  52. calling msg...
  53. additional concern
  54. msg method invoked
  55. calling m...
  56. additional concern
  57. m method invoked
  58. calling k...
  59. additional concern
  60. k method invoked

if you change the pointcut expression

before

  1. @Pointcut("execution(* Operation.*(..))")
  2. calling msg...
  3. additional concern
  4. msg method invoked
  5. calling m...
  6. additional concern
  7. m method invoked
  8. calling k...
  9. additional concern
  10. k method invoked

modify

  1. @Pointcut("execution(* Operation.m*(..))")

Now additional concern will be applied for the methods starting with m in Operation class

  1. calling msg...
  2. additional concern
  3. msg method invoked
  4. calling m...
  5. additional concern
  6. m method invoked
  7. calling k...
  8. k method invoked//have no "additional concern"

(3)@After

  1. public class Operation {
  2. public void msg(){
  3. System.out.println("msg method invoked");}
  4. public int m(){
  5. System.out.println("m method invoked");return 2;}
  6. public int k(){
  7. System.out.println("k method invoked");return 3;}
  8. }
  9. import org.aspectj.lang.JoinPoint;
  10. import org.aspectj.lang.annotation.After;
  11. import org.aspectj.lang.annotation.Aspect;
  12. import org.aspectj.lang.annotation.Pointcut;
  13. /**
  14. * @author: Amy
  15. * @create: 2023-02-20 15:05
  16. **/
  17. @Aspect
  18. public class TrackOperation {
  19. @Pointcut("execution(* Operation.*(..))")
  20. public void k(){
  21. }//pointcut name
  22. @After("k()")//applying pointcut on after advice
  23. public void myadvice(JoinPoint jp){
  24. System.out.println("additional concern");
  25. }
  26. }
  27. <?xml version="1.0" encoding="UTF-8"?>
  28. <beans
  29. xmlns="http://www.springframework.org/schema/beans"
  30. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  31. xmlns:p="http://www.springframework.org/schema/p"
  32. xsi:schemaLocation="http://www.springframework.org/schema/beans
  33. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  34. <bean id="op" class="com.amy.Operation"></bean>
  35. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  36. <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
  37. </beans>
  38. public class Test {
  39. public static void main(String[] args) {
  40. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  41. Operation o= (Operation) context.getBean("op");
  42. System.out.println("calling msg...");
  43. o.msg();
  44. System.out.println("calling m...");
  45. o.m();
  46. System.out.println("calling k...");
  47. o.k();
  48. }
  49. }
  50. calling msg...
  51. msg method invoked
  52. additional concern
  53. calling m...
  54. m method invoked
  55. additional concern
  56. calling k...
  57. k method invoked
  58. additional concern

(4) @AfterReturning

By using after returning advice, we can get the result in the advice.

  1. public class Operation {
  2. public int m(){
  3. System.out.println("m method invoked");return 2;}
  4. public int k(){
  5. System.out.println("k method invoked");return 3;}
  6. }
  7. package com.amy;
  8. import org.aspectj.lang.JoinPoint;
  9. import org.aspectj.lang.annotation.AfterReturning;
  10. import org.aspectj.lang.annotation.Aspect;
  11. /**
  12. * @author: Amy
  13. * @create: 2023-02-20 15:05
  14. **/
  15. @Aspect
  16. public class TrackOperation {
  17. @AfterReturning(
  18. pointcut = "execution(* Operation.*(..))",
  19. returning= "result")
  20. public void myadvice(JoinPoint jp,Object result){
  21. System.out.println("additional concern");
  22. System.out.println("Method Signature: " + jp.getSignature());
  23. System.out.println("Result in advice: "+result);
  24. System.out.println("end of after returning advice...");
  25. }
  26. }
  27. <?xml version="1.0" encoding="UTF-8"?>
  28. <beans
  29. xmlns="http://www.springframework.org/schema/beans"
  30. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  31. xmlns:p="http://www.springframework.org/schema/p"
  32. xsi:schemaLocation="http://www.springframework.org/schema/beans
  33. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  34. <bean id="op" class="com.amy.Operation"></bean>
  35. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  36. <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
  37. </beans>
  38. public class Test {
  39. public static void main(String[] args) {
  40. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  41. Operation o= (Operation) context.getBean("op");
  42. System.out.println("calling m...");
  43. o.m();
  44. System.out.println("calling k...");
  45. o.k();
  46. }
  47. }
  48. calling m...
  49. m method invoked
  50. additional concern
  51. Method Signature: int com.amy.Operation.m()
  52. Result in advice: 2
  53. end of after returning advice...
  54. calling k...
  55. k method invoked
  56. additional concern
  57. Method Signature: int com.amy.Operation.k()
  58. Result in advice: 3
  59. end of after returning advice...

(5) @Around

  • The AspectJ around advice is applied before and after calling the actual business logic methods.
  • Here, we are assuming that applicationContext.xml file is same as given in @Before example.

    public class Operation {

    1. public void msg(){
    2. System.out.println("msg() is invoked");}
    3. public void display(){
    4. System.out.println("display() is invoked");}

    }

    package com.amy;

  1. import org.aspectj.lang.ProceedingJoinPoint;
  2. import org.aspectj.lang.annotation.Around;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Pointcut;
  5. /**
  6. * @author: Amy
  7. * @create: 2023-02-20 15:05
  8. **/
  9. @Aspect
  10. public class TrackOperation {
  11. @Pointcut("execution(* Operation.*(..))")
  12. public void k(){
  13. }//pointcut name
  14. @Around("k()")//applying pointcut on before advice
  15. public Object myadvice(ProceedingJoinPoint jp) throws Throwable{
  16. //it is advice (before advice)
  17. System.out.println("Additional Concern Before calling actual method");
  18. Object obj = jp.proceed();
  19. System.out.println("Additional Concern After calling actual method");
  20. return obj;
  21. }
  22. }
  23. <?xml version="1.0" encoding="UTF-8"?>
  24. <beans
  25. xmlns="http://www.springframework.org/schema/beans"
  26. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  27. xmlns:p="http://www.springframework.org/schema/p"
  28. xsi:schemaLocation="http://www.springframework.org/schema/beans
  29. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  30. <bean id="op" class="com.amy.Operation"></bean>
  31. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  32. <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
  33. </beans>
  34. public class Test {
  35. public static void main(String[] args) {
  36. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  37. Operation o= (Operation) context.getBean("op");
  38. o.msg();
  39. o.display();
  40. }
  41. }
  42. Additional Concern Before calling actual method
  43. msg() is invoked
  44. Additional Concern After calling actual method
  45. Additional Concern Before calling actual method
  46. display() is invoked
  47. Additional Concern After calling actual method

(6)@AfterThrowing

  • By using after throwing advice, we can print the exception in the TrackOperation class.

    public class Operation {

    1. public void validate(int age)throws Exception{
    2. if(age<18){
    3. throw new ArithmeticException("Not valid age");
    4. }
    5. else{
    6. System.out.println("Thanks for vote");
    7. }
    8. }

    }

    package com.amy;

  1. import org.aspectj.lang.JoinPoint;
  2. import org.aspectj.lang.annotation.AfterThrowing;
  3. import org.aspectj.lang.annotation.Aspect;
  4. /**
  5. * @author: Amy
  6. * @create: 2023-02-20 15:05
  7. **/
  8. @Aspect
  9. public class TrackOperation {
  10. @AfterThrowing(
  11. pointcut = "execution(* Operation.*(..))",
  12. throwing= "error")
  13. public void myadvice(JoinPoint jp, Throwable error)//it is advice
  14. {
  15. System.out.println("additional concern");
  16. System.out.println("Method Signature: " + jp.getSignature());
  17. System.out.println("Exception is: "+error);
  18. System.out.println("end of after throwing advice...");
  19. }
  20. }
  21. <?xml version="1.0" encoding="UTF-8"?>
  22. <beans
  23. xmlns="http://www.springframework.org/schema/beans"
  24. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  25. xmlns:p="http://www.springframework.org/schema/p"
  26. xsi:schemaLocation="http://www.springframework.org/schema/beans
  27. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  28. <bean id="op" class="com.amy.Operation"></bean>
  29. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  30. <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
  31. </beans>
  32. public class Test {
  33. public static void main(String[] args) {
  34. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  35. Operation o= (Operation) context.getBean("op");
  36. try{
  37. o.validate(19);
  38. }catch(Exception e){
  39. System.out.println(e);}
  40. System.out.println("calling validate again...");
  41. try{
  42. o.validate(11);
  43. }catch(Exception e){
  44. System.out.println(e);}
  45. }
  46. }
  47. Thanks for vote
  48. calling validate again...
  49. additional concern
  50. Method Signature: void com.amy.Operation.validate(int)
  51. Exception is: java.lang.ArithmeticException: Not valid age
  52. end of after throwing advice...
  53. java.lang.ArithmeticException: Not valid age

2)By xml configuration (schema based)

  • Spring enables you to define the aspects, advices and pointcuts in xml file.
    aop:before It is applied before calling the actual business logic method.
    aop:after It is applied after calling the actual business logic method.
    aop:after-returning it is applied after calling the actual business logic method. It can be used to intercept the return value in advice.
    aop:aroundIt is applied before and after calling the actual business logic method.
    aop:after-throwing It is applied if actual business logic method throws exception.

(1) aop:before

  1. public class Operation {
  2. public void msg(){
  3. System.out.println("msg method invoked");}
  4. public int m(){
  5. System.out.println("m method invoked");return 2;}
  6. public int k(){
  7. System.out.println("k method invoked");return 3;}
  8. }
  9. public class TrackOperation {
  10. public void myadvice(JoinPoint jp)//it is advice
  11. {
  12. System.out.println("additional concern");
  13. }
  14. }
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <beans xmlns="http://www.springframework.org/schema/beans"
  17. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  18. xmlns:aop="http://www.springframework.org/schema/aop"
  19. xsi:schemaLocation="http://www.springframework.org/schema/beans
  20. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  21. http://www.springframework.org/schema/aop
  22. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
  23. <aop:aspectj-autoproxy />
  24. <bean id="op" class="com.amy.Operation"></bean>
  25. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  26. <aop:config>
  27. <aop:aspect id="myaspect" ref="trackOperation">
  28. <!-- @Before -->
  29. <aop:pointcut id="pointCutBefore" expression="execution(* com.amy.Operation.*(..))"/>
  30. <aop:before method="myadvice" pointcut-ref="pointCutBefore" />
  31. </aop:aspect>
  32. </aop:config>
  33. </beans>
  34. public class Test {
  35. public static void main(String[] args) {
  36. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  37. Operation o= (Operation) context.getBean("op");
  38. System.out.println("calling msg...");
  39. o.msg();
  40. System.out.println("calling m...");
  41. o.m();
  42. System.out.println("calling k...");
  43. o.k();
  44. }
  45. }
  46. calling msg...
  47. additional concern
  48. msg method invoked
  49. calling m...
  50. additional concern
  51. m method invoked
  52. calling k...
  53. additional concern
  54. k method invoked

(2)aop:after

  1. public class Operation {
  2. public void msg(){
  3. System.out.println("msg method invoked");}
  4. public int m(){
  5. System.out.println("m method invoked");return 2;}
  6. public int k(){
  7. System.out.println("k method invoked");return 3;}
  8. }
  9. public class TrackOperation {
  10. public void myadvice(JoinPoint jp)//it is advice
  11. {
  12. System.out.println("additional concern");
  13. }
  14. }
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <beans xmlns="http://www.springframework.org/schema/beans"
  17. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  18. xmlns:aop="http://www.springframework.org/schema/aop"
  19. xsi:schemaLocation="http://www.springframework.org/schema/beans
  20. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  21. http://www.springframework.org/schema/aop
  22. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
  23. <aop:aspectj-autoproxy />
  24. <bean id="op" class="com.amy.Operation"></bean>
  25. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  26. <aop:config>
  27. <aop:aspect id="myaspect" ref="trackOperation">
  28. <!-- @After -->
  29. <aop:pointcut id="pointCutAfter" expression="execution(* com.amy.Operation.*(..))" />
  30. <aop:after method="myadvice" pointcut-ref="pointCutAfter" />
  31. </aop:aspect>
  32. </aop:config>
  33. </beans>
  34. public class Test {
  35. public static void main(String[] args) {
  36. ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
  37. Operation o= (Operation) context.getBean("op");
  38. System.out.println("calling msg...");
  39. o.msg();
  40. System.out.println("calling m...");
  41. o.m();
  42. System.out.println("calling k...");
  43. o.k();
  44. }
  45. }
  46. calling msg...
  47. msg method invoked
  48. additional concern
  49. calling m...
  50. m method invoked
  51. additional concern
  52. calling k...
  53. k method invoked
  54. additional concern

(3)aop:after-returning

  1. public class Operation {
  2. public int m(){
  3. System.out.println("m method invoked");return 2;}
  4. public int k(){
  5. System.out.println("k method invoked");return 3;}
  6. }
  7. public class TrackOperation {
  8. public void myadvice(JoinPoint jp,Object result)//it is advice (after advice)
  9. {
  10. System.out.println("additional concern");
  11. System.out.println("Method Signature: " + jp.getSignature());
  12. System.out.println("Result in advice: "+result);
  13. System.out.println("end of after returning advice...");
  14. }
  15. }
  16. <?xml version="1.0" encoding="UTF-8"?>
  17. <beans xmlns="http://www.springframework.org/schema/beans"
  18. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  19. xmlns:aop="http://www.springframework.org/schema/aop"
  20. xsi:schemaLocation="http://www.springframework.org/schema/beans
  21. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  22. http://www.springframework.org/schema/aop
  23. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
  24. <aop:aspectj-autoproxy />
  25. <bean id="op" class="com.amy.Operation"></bean>
  26. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  27. <aop:config>
  28. <aop:aspect id="myaspect" ref="trackOperation">
  29. <!-- @AfterReturning -->
  30. <aop:pointcut id="pointCutAfterReturning" expression="execution(* com.amy.Operation.*(..))" />
  31. <aop:after-returning method="myadvice" returning="result" pointcut-ref="pointCutAfterReturning" />
  32. </aop:aspect>
  33. </aop:config>
  34. </beans>
  35. public class Test {
  36. public static void main(String[] args) {
  37. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  38. Operation o = (Operation) context.getBean("op");
  39. System.out.println("calling m...");
  40. System.out.println(o.m());
  41. System.out.println("calling k...");
  42. System.out.println(o.k());
  43. }
  44. }
  45. calling m...
  46. m method invoked
  47. additional concern
  48. Method Signature: int com.amy.Operation.m()
  49. Result in advice: 2
  50. end of after returning advice...
  51. 2
  52. calling k...
  53. k method invoked
  54. additional concern
  55. Method Signature: int com.amy.Operation.k()
  56. Result in advice: 3
  57. end of after returning advice...
  58. 3

(4)aop:around

  1. public class Operation {
  2. public void msg(){
  3. System.out.println("msg() is invoked");}
  4. public void display(){
  5. System.out.println("display() is invoked");}
  6. }
  7. public class TrackOperation {
  8. public Object myadvice(ProceedingJoinPoint pjp) throws Throwable
  9. {
  10. System.out.println("Additional Concern Before calling actual method");
  11. Object obj=pjp.proceed();
  12. System.out.println("Additional Concern After calling actual method");
  13. return obj;
  14. }
  15. }
  16. <?xml version="1.0" encoding="UTF-8"?>
  17. <beans xmlns="http://www.springframework.org/schema/beans"
  18. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  19. xmlns:aop="http://www.springframework.org/schema/aop"
  20. xsi:schemaLocation="http://www.springframework.org/schema/beans
  21. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  22. http://www.springframework.org/schema/aop
  23. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
  24. <aop:aspectj-autoproxy />
  25. <bean id="op" class="com.amy.Operation"></bean>
  26. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  27. <aop:config>
  28. <aop:aspect id="myaspect" ref="trackOperation">
  29. <!-- @Around -->
  30. <aop:pointcut id="pointCutAround" expression="execution(* com.amy.Operation.*(..))" />
  31. <aop:around method="myadvice" pointcut-ref="pointCutAround" /> </aop:aspect>
  32. </aop:config>
  33. </beans>
  34. public class Test {
  35. public static void main(String[] args) {
  36. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  37. Operation o = (Operation) context.getBean("op");
  38. o.msg();
  39. o.display();
  40. }
  41. }
  42. Additional Concern Before calling actual method
  43. msg() is invoked
  44. Additional Concern After calling actual method
  45. Additional Concern Before calling actual method
  46. display() is invoked
  47. Additional Concern After calling actual method

(5)aop:after-throwing

  1. public class Operation {
  2. public void validate(int age)throws Exception{
  3. if(age<18){
  4. throw new ArithmeticException("Not valid age");
  5. }
  6. else{
  7. System.out.println("Thanks for vote");
  8. }
  9. }
  10. }
  11. public class TrackOperation {
  12. public void myadvice(JoinPoint jp,Throwable error)//it is advice
  13. {
  14. System.out.println("additional concern");
  15. System.out.println("Method Signature: " + jp.getSignature());
  16. System.out.println("Exception is: "+error);
  17. System.out.println("end of after throwing advice...");
  18. }
  19. }
  20. <?xml version="1.0" encoding="UTF-8"?>
  21. <beans xmlns="http://www.springframework.org/schema/beans"
  22. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  23. xmlns:aop="http://www.springframework.org/schema/aop"
  24. xsi:schemaLocation="http://www.springframework.org/schema/beans
  25. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  26. http://www.springframework.org/schema/aop
  27. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
  28. <aop:aspectj-autoproxy />
  29. <bean id="op" class="com.amy.Operation"></bean>
  30. <bean id="trackOperation" class="com.amy.TrackOperation"></bean>
  31. <aop:config>
  32. <aop:aspect id="myaspect" ref="trackOperation">
  33. <!-- @AfterThrowing -->
  34. <aop:pointcut id="pointCutAfterThrowing" expression="execution(* com.amy.Operation.*(..))" />
  35. <aop:after-throwing method="myadvice" throwing="error" pointcut-ref="pointCutAfterThrowing" />
  36. </aop:aspect>
  37. </aop:config>
  38. </beans>
  39. public class Test {
  40. public static void main(String[] args) {
  41. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  42. Operation o = (Operation) context.getBean("op");
  43. System.out.println("calling validate...");
  44. try{
  45. o.validate(19);
  46. }catch(Exception e){
  47. System.out.println(e);}
  48. System.out.println("calling validate again...");
  49. try{
  50. o.validate(11);
  51. }catch(Exception e){
  52. System.out.println(e);}
  53. }
  54. }
  55. calling validate...
  56. Thanks for vote
  57. calling validate again...
  58. additional concern
  59. Method Signature: void com.amy.Operation.validate(int)
  60. Exception is: java.lang.ArithmeticException: Not valid age
  61. end of after throwing advice...
  62. java.lang.ArithmeticException: Not valid age

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring AOP详细介绍

    AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想,是个比较经典的例子。 一 AO