去面试Java绝对少不了的就是AOP(切面编程),我也纳闷,AOP就这么重要么,后来看了Spring实战之后发现,AOP就是Spring的很多特性的基础,日志记录,性能统计,安全控制,事务处理,异常处理等等。
这篇文章,我们简单的写一个demo体会一下AOP,后面我们再详细介绍。
还记得上一篇 讲了一个人类打电话的例子,既然是打电话,打之前少不了拨号的操作,打完之后少不了挂电话的操作。那我们就在打电话(call)的方法,这个切点上添加拨号和挂电话的操作。
为了演示切面操作,需要引入一个aspectj的包,在pom.xml里增加:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
新增一个类电话操作类:
public class PhoneOperation {
public void dial(){
System.out.println("Dialing");
}
public void hangUp(){
System.out.println("after hand up the phone");
}
}
在resources/spring先新增一个新的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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="phone" class="TelePhone">
</bean>
<bean name="human" class="ChaneseHuman">
<property name="phone" ref="phone"/>
</bean>
<bean name="phoneOperation" class="PhoneOperation">
</bean>
<aop:config>
<aop:aspect ref="phoneOperation">
<aop:pointcut id="operation" expression="execution(* Phone*.call())"/>
<aop:before method="dial" pointcut-ref="operation"/>
<aop:after method="hangUp" pointcut-ref="operation"/>
</aop:aspect>
</aop:config>
</beans>
多了一个aop:config元素,这里不细讲aop:config元素有哪儿写操作,后续会讲解了。
修改我的main方法:
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/aop.xml");
Human human = applicationContext.getBean(Human.class);
human.call();
执行结果:
Dialing
I am calling by telephone!
after hand up the phone