SpringAOP

                    SpringAOP

1.配置pom.xml

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4 
 5   <groupId>cn.edu.sdau</groupId>
 6   <artifactId>SpringAOPdemo</artifactId>
 7   <version>1.0-SNAPSHOT</version>
 8   <packaging>jar</packaging>
 9 
10   <name>SpringAOPdemo</name>
11   <url>http://maven.apache.org</url>
12 
13   <properties>
14  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
16  <maven.compiler.encoding>UTF-8</maven.compiler.encoding> 
17  <maven.compiler.source>1.8</maven.compiler.source>
18  <maven.compiler.target>1.8</maven.compiler.target>    
19  <java.version>1.8</java.version>
20  <spring.version>5.3.13</spring.version>
21 </properties>
22 
23   <dependencies>
24   <!-- https://mvnrepository.com/artifact/org.springframework/spring-core--> 
25 <dependency>
26     <groupId>org.springframework</groupId>
27     <artifactId>spring-core</artifactId>
28     <version>${spring.version}</version>
29 </dependency>
30  <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
31 <dependency>
32     <groupId>org.springframework</groupId>
33     <artifactId>spring-aop</artifactId>
34     <version>${spring.version}</version>
35 </dependency>
36   <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
37 <dependency>
38     <groupId>org.springframework</groupId>
39     <artifactId>spring-context</artifactId>
40     <version>${spring.version}</version>
41 </dependency>
42 <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
43 <dependency>
44     <groupId>org.springframework</groupId>
45     <artifactId>spring-aspects</artifactId>
46     <version>${spring.version}</version>
47 </dependency>
48 
49 
50 
51 
52     <dependency>
53       <groupId>junit</groupId>
54       <artifactId>junit</artifactId>
55       <version>3.8.1</version>
56       <scope>test</scope>
57     </dependency>
58   </dependencies>
59 </project>

2.建立bean类

 

  1 package cn.edu.sdau;
  2 
  3 public class A {
  4     private String a1;
  5     private String a2;
  6     
  7     public void mA1(){
  8         System.out.println("我是A类的方法mA1(),被运行!");
  9         for(int i = 0; i < 100000000; i++);        
 10     }
 11     public void mA2(){
 12         System.out.println("我是A类的方法mA2(),被运行!");
 13         for(int i = 0; i < 100000000; i++);
 14     }    
 15     public A() {}
 16     public A(String a1, String a2) {        
 17         this.a1 = a1;
 18         this.a2 = a2;
 19     }
 20     public String getA1() {
 21         return a1;
 22     }
 23     public void setA1(String a1) {
 24         this.a1 = a1;
 25     }
 26     public String getA2() {
 27         return a2;
 28     }
 29     public void setA2(String a2) {
 30         this.a2 = a2;
 31     }
 32 }package cn.edu.sdau;
 33 
 34 public class B {
 35     private String b1;
 36     private String b2;
 37     public void mB1(){
 38         System.out.println("我是B类的方法mB1(),被运行!");
 39         double i=0;
 40         while(i<10e+8){
 41             i=i+1;
 42         }
 43         //for(long i = 0; i <300000000; i++);
 44     }
 45     public void mB2(){
 46         System.out.println("我是B类的方法mB2(),被运行!");
 47         double i=0;
 48         while(i<10e+8){
 49             i=i+1;
 50         }
 51         //for(int i = 0; i < 250000000; i++);
 52     }    
 53     
 54     public B() {}
 55     public B(String b1, String b2) {    
 56         this.b1 = b1;
 57         this.b2 = b2;
 58     }
 59     public String getB1() {
 60         return b1;
 61     }
 62     public void setB1(String b1) {
 63         this.b1 = b1;
 64     }
 65     public String getB2() {
 66         return b2;
 67     }
 68     public void setB2(String b2) {
 69         this.b2 = b2;
 70     }
 71 }
 72 package cn.edu.sdau;
 73 public class C {
 74     private String c1;
 75     private String c2;
 76     public void mC1(){
 77         System.out.println("我是C类的方法mC1(),被运行!");
 78         for(int i = 0; i < 300000000; i++);
 79     }
 80     public void mC2(){
 81         System.out.println("我是C类的方法mC2(),被运行!");
 82         for(int i = 0; i < 300000000; i++);
 83     }
 84     
 85     public C() {}
 86     public C(String c1, String c2) {        
 87         this.c1 = c1;
 88         this.c2 = c2;
 89     }
 90     public String getC1() {
 91         return c1;
 92     }
 93     public void setC1(String c1) {
 94         this.c1 = c1;
 95     }
 96     public String getC2() {
 97         return c2;
 98     }
 99     public void setC2(String c2) {
100         this.c2 = c2;
101     }
102 }
103 package cn.edu.sdau;
104 import java.text.SimpleDateFormat;
105 import java.util.Calendar;
106 
107 import org.aspectj.lang.JoinPoint;
108 
109 public class X {
110     public void mX1(JoinPoint joinPoint) {
111         // 连接点对象做参数,利用该参数,获取目标对象的方法
112         String methodName = joinPoint.getSignature().getName();
113         String className = joinPoint.getTarget().getClass().getSimpleName();
114         System.out.println("我是前置通知,在"+className+"类方法:" + methodName + "()运行前被切入!");
115         // 获取当前系统的时间,并转换为yyyy年MM月dd日 HH:mm:ss格式,并显示
116         Calendar startTimeNow = Calendar.getInstance();
117         SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
118         String startTime = fmt.format(startTimeNow.getTime());
119         System.out.println(className+"类方法:" + methodName + "(),运行开始时间:" + startTime);
120     }
121 
122     public void mX2(JoinPoint joinPoint) {
123         // 连接点对象做参数,利用该参数,获取目标对象的方法
124         String methodName = joinPoint.getSignature().getName();
125         String className = joinPoint.getTarget().getClass().getSimpleName();
126         System.out.println("我是后置通知,在"+className+"类方法:" + methodName + "()运行前被切入!");
127         // 获取当前系统的时间,并转换为yyyy年MM月dd日 HH:mm:ss格式,并显示
128         Calendar endTimeNow = Calendar.getInstance();
129         SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
130         String endTime = fmt.format(endTimeNow.getTime());
131         System.out.println(className+"类方法:" + methodName + "(),运行结束时间:" + endTime);
132     }
133 
134 }

  1 package cn.edu.sdau;
  2 
  3 public interface ArithmeticCalculator {
  4     public int add(int i, int j);
  5     public int sub(int i, int j);
  6     public int mul(int i, int j);
  7     public int div(int i, int j);
  8 }
  9 package cn.edu.sdau;
 10 
 11 public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
 12     @Override
 13     public int add(int i, int j) {
 14         int result = i + j;
 15         return result;
 16     }
 17 
 18     @Override
 19     public int sub(int i, int j) {
 20         int result = i - j;
 21         return result;
 22     }
 23 
 24     @Override
 25     public int mul(int i, int j) {
 26         int result = i * j;
 27         return result;
 28     }
 29 
 30     @Override
 31     public int div(int i, int j) {
 32         int result = i / j;
 33         return result;
 34     }
 35 
 36 }
 37 
 38 package cn.edu.sdau;
 39 
 40 import org.springframework.stereotype.Component;
 41 
 42 @Component("xyz") //注释bean组件
 43 public class ArithmeticCalculatorImpl2  implements ArithmeticCalculator{
 44     @Override
 45     public int add(int i, int j) {
 46         int result = i + j;
 47         return result;
 48     }
 49 
 50     @Override
 51     public int sub(int i, int j) {
 52         int result = i - j;
 53         return result;
 54     }
 55 
 56     @Override
 57     public int mul(int i, int j) {
 58         int result = i * j;
 59         return result;
 60     }
 61 
 62     @Override
 63     public int div(int i, int j) {
 64         int result = i / j;
 65         return result;
 66     }
 67 
 68 }
 69 
 70 
 71 package cn.edu.sdau;
 72 
 73 import java.util.Arrays;
 74 
 75 import org.aspectj.lang.JoinPoint;
 76 public class LoggingAspect {
 77     public void beforeMethod(JoinPoint joinPoint){
 78         String methodName = joinPoint.getSignature().getName();
 79         Object [] args = joinPoint.getArgs();
 80         System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
 81 
 82     }
 83 
 84     public void afterMethod(JoinPoint joinPoint){
 85         String methodName = joinPoint.getSignature().getName();
 86         System.out.println("The method " + methodName + " ends");
 87 
 88     }
 89 
 90 }
 91 package cn.edu.sdau;
 92 import java.util.Arrays;
 93 
 94 import org.aspectj.lang.JoinPoint;
 95 import org.aspectj.lang.annotation.After;
 96 import org.aspectj.lang.annotation.Aspect;
 97 import org.aspectj.lang.annotation.Before;
 98 import org.springframework.core.annotation.Order;
 99 import org.springframework.stereotype.Component;
100 
101 @Order(2)
102 // 注释切面的优先级别,数字越小,级别越高
103 @Aspect
104 // 通过添加 @Aspect 注解声明一个 bean 是一个切面!
105 @Component
106 // 通过添加@Component 注解声明一个 bean !
107 public class LoggingAspectAnnotation {
108     // 注释前置通知及其切入点表达式
109     @Before("execution(public int cn.edu.sdau.ArithmeticCalculator.add(int,int))")
110     public void beforeMethod(JoinPoint joinPoint) {
111         String methodName = joinPoint.getSignature().getName();
112         Object[] args = joinPoint.getArgs();
113         System.out.println("The method " + methodName + " begins with "
114                 + Arrays.asList(args));
115     }
116 
117     // 注释后置通知及其切入点表达式
118     @After("execution(* cn.edu.sdau.ArithmeticCalculator.*(..))")
119     public void afterMethod(JoinPoint joinPoint) {
120         String methodName = joinPoint.getSignature().getName();
121         System.out.println("The method " + methodName + " ends");
122     }
123 }
124 
125 
126 package cn.edu.sdau;
127 import java.util.Arrays;
128 
129 import org.aspectj.lang.JoinPoint;
130 public class VlidationAspect {
131 
132     public void validateArgs(JoinPoint joinPoint){
133         String methodName = joinPoint.getSignature().getName();
134         //取得参数.
135         Object [] args = joinPoint.getArgs();
136         System.out.println("-->validate:" + Arrays.asList(args));
137         if (args != null && args.length > 0) {
138             for(int i=0;i<args.length;++i){
139                 if(((Integer)args[i]).intValue()<0){
140                     System.out.println("警告:方法"+methodName+"()第"+i+"参数为负数:" +args[i]);
141                 }
142             }
143         }
144     }package cn.edu.sdau;
145 import java.util.Arrays;
146 
147 import org.aspectj.lang.JoinPoint;
148 public class VlidationAspect {
149 
150     public void validateArgs(JoinPoint joinPoint){
151         String methodName = joinPoint.getSignature().getName();
152         //取得参数.
153         Object [] args = joinPoint.getArgs();
154         System.out.println("-->validate:" + Arrays.asList(args));
155         if (args != null && args.length > 0) {
156             for(int i=0;i<args.length;++i){
157                 if(((Integer)args[i]).intValue()<0){
158                     System.out.println("警告:方法"+methodName+"()第"+i+"参数为负数:" +args[i]);
159                 }
160             }
161         }
162     }
163 }
164 }

 1 package cn.edu.sdau;
 2 import java.util.Arrays;
 3 
 4 import org.aspectj.lang.JoinPoint;
 5 import org.aspectj.lang.annotation.Aspect;
 6 import org.aspectj.lang.annotation.Before;
 7 import org.springframework.core.annotation.Order;
 8 import org.springframework.stereotype.Component;
 9 
10 @Order(1)  //注释切面的优先级别,数字越小,级别越高
11 @Aspect    // 注释为一个切面
12 @Component //注释为一个bean组件
13 public class VlidationAspectAnnotation {
14     //注释为“前置通知,并注释其切入点表达式”
15     @Before("execution(* cn.edu.sdau.ArithmeticCalculator.*(..))")
16     public void validateArgs(JoinPoint joinPoint) {
17         String methodName = joinPoint.getSignature().getName();
18         // 取得参数.
19         Object[] args = joinPoint.getArgs();
20         System.out.println("-->validate:" + Arrays.asList(args));
21         if (args != null && args.length > 0) {
22             for (int i = 0; i < args.length; ++i) {
23                 if (((Integer) args[i]).intValue() < 0) {
24                     System.out.println("警告:方法" + methodName + "()第" + i
25                             + "参数为负数:" + args[i]);
26                 }
27             }
28         }
29     }
30 
31 }

 

3.配置sping.xml(不自动装配)(配置顺序不能改变)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
 7 
 8     <!-- 配置 bean -->
 9     <bean id="a" class="cn.edu.sdau.A"></bean>
10     <bean id="b" class="cn.edu.sdau.B"></bean>
11     <bean id="c" class="cn.edu.sdau.C"></bean>
12     <bean id="x" class="cn.edu.sdau.X"></bean>
13 
14     <bean id="abcd" class="cn.edu.sdau.ArithmeticCalculatorImpl"></bean>
15 
16     <!-- 配置切面类的一个bean -->
17     <bean id="logging" class="cn.edu.sdau.LoggingAspect"></bean>
18     <bean id="xyz" class="cn.edu.sdau.VlidationAspect"></bean>
19     
20     
21     <!-- 配置 AOP -->
22     <aop:config>
23         <!-- 配置切面及通知 -->
24         <aop:aspect ref="logging" order="2">
25             <aop:before method="beforeMethod"
26                         pointcut="execution(* cn.edu.sdau.ArithmeticCalculator.*(..))" />
27             <aop:after method="afterMethod"
28                        pointcut="execution(* cn.edu.sdau.ArithmeticCalculator.*(..))" />
29         </aop:aspect>
30 
31         <!-- 配置第2个切面及通知 -->
32         <aop:aspect ref="xyz" order="1">
33             <aop:before method="validateArgs"
34                         pointcut="execution(* cn.edu.sdau.ArithmeticCalculator.*(..))" />
35         </aop:aspect>
36     </aop:config>
37     <aop:config>        
38         <!-- 配置切面及通知 -->
39         <aop:aspect ref="x">
40             <aop:before method="mX1" 
41                              pointcut="execution(* cn.edu.sdau.*.*())"/>
42             <aop:after method="mX2" 
43                             pointcut="execution(* cn.edu.sdau.*.*())"/>    
44         </aop:aspect>            
45     </aop:config>
46     
47 </beans>


3.2自动装配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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="cn.edu"></context:component-scan>

<!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

 

4.测试app1

 1 package cn.edu.sdau;
 2 
 3 /**
 4  * Hello world!
 5  *
 6  */
 7 import org.springframework.context.ApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 
10 public class App {    
11     public static void main(String[] args) {        
12         //(1)创建IoC容器        
13         ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
14         //(2)从容器IoC中获取对象
15         A a = (A) ctx.getBean("a");
16         B b = (B) ctx.getBean("b");
17         C c = (C) ctx.getBean("c");
18         //(3)使用对象
19         a.mA1();
20         b.mB2();
21         a.mA2();
22         b.mB1();
23         c.mC1();
24         
25     }    
26 }

4.2测试app2

 1 package cn.edu.sdau;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 public class app2 {
 6     public static void main(String[] args) {
 7         //(1)创建IoC容器
 8         String pathName="spring.xml";
 9         ApplicationContext ctx = new ClassPathXmlApplicationContext(pathName);
10         //(2)从容器IoC中获取对象(在类中已经采用注释)
11         ArithmeticCalculator ac = (ArithmeticCalculator) ctx.getBean("abcd");
12         //(3)使用对象
13         int result = ac.add(10, 20);
14         System.out.println("result:" + result);
15         result = ac.div(-21, 3);
16         System.out.println("result:" + result);
17     }
18 
19 }

 

 

 

4.3测试app3

 1 package cn.edu.sdau;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 public class app3 {
 6     public static void main(String[] args) {
 7 
 8         ApplicationContext ctx = new ClassPathXmlApplicationContext("spring2.xml");
 9         ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("xyz");
10 
11         int result = arithmeticCalculator.add(10, 20);
12         System.out.println("result:" + result);
13 
14         result = arithmeticCalculator.div(-21, 3);
15         System.out.println("result:" + result);
16     }
17 
18 }

 

posted @ 2021-12-03 12:42  坤k  阅读(41)  评论(2)    收藏  举报