自己关于AOP的一些理解:
与各业务逻辑没有必然耦合性的功能模块称为aspect(由pointcut跟advise组成),这些模块可以从业务逻辑中抽取出来单独编写,然后通过AOP织入各业务逻辑,即所谓的面向切片。AOP使用的应该是动态代理的机制,如果在一个业务逻辑中找到了pointcut,则将advise织入,返回一个代理,拿到的对象就是一个与原对象同名的代理对象,其中的方法是已经织入了切片的方法。
下面是入门之后写的一个例子,本例子使用静态配置的方式编写,还可以使用注解的方式编写。
目录结构:
aspect:
public class checkHandler {
private void checkFinished(){
System.out.println("______checkFinished_______");
}
private void checkMember(){
System.out.println("---------this is a member!----------");
}
}
让用户与会员管理中织入检验完成与检验会员功能。
原用户管理与会员管理:
public class userManagerImpl implements userManager{
public void addUser() {
System.out.println("_________addUser()_________");
}
public void delUser() {
System.out.println("_____________delUser()______________");
}
public int getUserNum() {
return 0;
}
public void memberLogin() {
System.out.println("userLogin!");
}
}
package testPackge;
public class memberManagerImpl implements memberManager{
public void memberLogin(){
System.out.println("________memberLoginSuccess!________");
}
}
aop配置文件:
配置切入点为任意对象的任意以add开头的方法末尾织入checkHandler的checkFinisherd方法。
切入点为testPackge包内的任意对象的任意方法末尾织入checkMember方法。
<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-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id = "usermanager" class = "userManagerImpl"/>
<bean id = "checkHandler" class = "checkHandler"/>
<bean id = "memberManager" class = "testPackge.memberManagerImpl"/>
<aop:config>
<aop:aspect id="myAspect" ref="checkHandler">
<aop:pointcut id = "checkFin" expression = "execution(* add*(..))"/>
<aop:pointcut id = "memcheck" expression = "execution(* testPackge.*.*(..))"/>
<aop:after method = "checkFinished" pointcut-ref = "checkFin"/>
<aop:after method = "checkMember" pointcut-ref = "memcheck"/>
</aop:aspect>
</aop:config>
</beans>
客户端:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import testPackge.memberManager;
public class client {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
userManager manager = (userManager)factory.getBean("usermanager");
memberManager mmanager = (memberManager)factory.getBean("memberManager");
manager.addUser();
mmanager.memberLogin();
manager.memberLogin();
}
}
运行结果:
_________addUser()_________
______checkFinished_______
________memberLoginSuccess!________
---------this is a member!----------
userLogin!看到已经织入完成,但是用户管理中的memberLogin并没有织入advise,因为没有配置这个类的切入点。