1. Spring AOP(Aspect-Oriented Programming)的概念和术语
1.1 什么是面向切面的编程
想象场景:
例如在操作数据库涉及到事务的时候,首先需要开启事物,然后执行sql语句,执行完sql语句之后,在提交事物。这样才算完成整个数据库的操作
切面(Aspect):通知和切点的结合,通知和切点定义了切面的全部内容——它是什么,在何时何处完成其功能
通知(Advice):通知定义了切面是什么以及何时调用,应该在某个方法前面调用,还是在后面调用。或者抛出异常时调用。
切点: 如果说通知定义了切面的“什么”或者“何时”的话,那么切点就定义了何处。通常是使用正则表达式定义所匹配的类和方法名称来指定切点
execution(* springaop.HelloWorld.*(..))
execution:表示在执行方法时触发
* 表示返回任意类型,
springaop.HelloWorld:表示springaop包下的HelloWorld接口
接下来的* 表示任意方法(..)任意的参数类型
2. SPRING AOP的例子
package springaop;
public interface HelloWorld
{
void printHelloWorld();
void doPrint();
}
package springaop;
public class HelloWorldImpl1 implements HelloWorld
{
public void printHelloWorld()
{
System.out.println("Enter HelloWorldImpl1.printHelloWorld()");
}
public void doPrint()
{
System.out.println("Enter HelloWorldImpl1.doPrint()");
return ;
}
}
package springaop;
public class HelloWorldImpl2 implements HelloWorld
{
public void printHelloWorld()
{
System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
}
public void doPrint()
{
System.out.println("Enter HelloWorldImpl2.doPrint()");
return ;
}
}
package springaop;
public class TimeHandler
{
public void printTime()
{
System.out.println("CurrentTime = " + System.currentTimeMillis());
}
}
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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 id="helloWorldImpl1" class="springaop.HelloWorldImpl1" />
<bean id="helloWorldImpl2" class="springaop.HelloWorldImpl2" />
<bean id="timeHandler" class="springaop.TimeHandler" />
<aop:config>
<aop:aspect id="time" ref="timeHandler">
<aop:pointcut id="addAllMethod" expression="execution(* springaop.HelloWorld.*(..))" />
<aop:before method="printTime" pointcut-ref="addAllMethod" />
<aop:after method="printTime" pointcut-ref="addAllMethod" />
</aop:aspect>
</aop:config>
</beans>
ApplicationContext ctx = new ClassPathXmlApplicationContext("aop.xml");
HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1");
HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2");
hw1.printHelloWorld();
System.out.println();
hw1.doPrint();
System.out.println();
hw2.printHelloWorld();
System.out.println();
hw2.doPrint();