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