回见Java框架spring Boot学习笔记(十三):aop实例操作,这里介绍注解aop操作
首先编写一个切入点HelloWorld.java
1 package com.example.spring; 2 3 public class HelloWorld { 4 public void printHello(){ 5 System.out.println("Hello Aop."); 6 } 7 }
编写切面TimeHandler.java
1 package com.example.spring; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.After; 5 import org.aspectj.lang.annotation.Around; 6 import org.aspectj.lang.annotation.Aspect; 7 import org.aspectj.lang.annotation.Before; 8 9 //使用@Aspect注解轻松定义切面 10 @Aspect 11 public class TimeHandler { 12 13 // 在方法上面使用注解完成前置增强配置 14 @Before(value = "execution(* com.example.spring.HelloWorld.*(..))") 15 public void beforTime() 16 { 17 System.out.println("前置增强:CurrentTime = " + System.currentTimeMillis()); 18 } 19 20 // 在方法上面使用注解完成后置增强配置 21 @After(value = "execution(* com.example.spring.HelloWorld.*(..))") 22 public void afterTime() 23 { 24 System.out.println("后置增强:CurrentTime = " + System.currentTimeMillis()); 25 } 26 27 // 在方法上面使用注解完成环绕增强配置 28 @Around(value = "execution(* com.example.spring.HelloWorld.*(..))") 29 public void aroundTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 30 //方法之前 31 System.out.println("环绕增强:CurrentTime = " + System.currentTimeMillis()); 32 33 //执行被增强的方法 34 proceedingJoinPoint.proceed(); 35 36 //方法之后 37 System.out.println("环绕增强:CurrentTime = " + System.currentTimeMillis()); 38 } 39 }
编写配置文件aop.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 6 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 7 http://www.springframework.org/schema/aop 8 http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> 9 10 <!-- bean definition & AOP specific configuration --> 11 <!-- 1 配置对象--> 12 <bean id="helloWorld" class="com.example.spring.HelloWorld"/> 13 <bean id="timeHandler" class="com.example.spring.TimeHandler"/> 14 15 <!-- 2 开启aop操作--> 16 <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 17 18 </beans>
编写运行文件Application.java
1 package com.example.spring; 2 3 import org.springframework.context.support.AbstractApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Application { 7 public static void main(String[] args) { 8 //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml 9 //使用AbstractApplicationContext容器 10 AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\aop.xml"); 11 //得到配置创建的对象 12 HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld"); 13 helloWorld.printHello(); 14 } 15 }
运行输出
环绕增强:CurrentTime = 1510208830742 前置增强:CurrentTime = 1510208830742 Hello Aop. 环绕增强:CurrentTime = 1510208830750 后置增强:CurrentTime = 1510208830750