前言
AOP编程也叫作面向切面编程,底层采用的是代理机制实现的。在Spring中,目标类有接口,也有类的时候,spring底层用动态代理实现;如果目标类只有类,spring底层用cglib实现。本篇笔记主要记录了通过工厂bean代理和AOP的简单案例。
一、AOP联盟通知类型
- 前置通知 org.springframework.aop.MethodBeforeAdvice — 在目标方法执行前实施增强
- 后置通知 org.springframework.aop.AfterReturningAdvice — 在目标方法执行后实施增强
- 环绕通知 org.aopalliance.intercept.MethodInterceptor — 在目标方法执行前后实施增强
- 异常抛出通知 org.springframework.aop.ThrowsAdvice — 在方法抛出异常后实施增强
- 引介通知 org.springframework.aop.IntroductionInterceptor — 在目标类中添加一些新的方法和属性
二、工厂bean代理
<需要aop联盟的jar包 – aopalliance;spring-aop实现>
1.目标类
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("add user");
}
}
2.切面类
确定通知,需要实现不同接口,环绕通知 — MethodInterceptor
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("前");
//手动执行目标方法
Object object = methodInvocation.proceed();
System.out.println("后");
return object;
}
}
3.Spring配置
<bean id="userService" class="com.spr.factorybean.UserServiceImpl"></bean>
<bean id="myAspect" class="com.spr.factorybean.MyAspect"></bean>
<bean id="proxyService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="com.spr.factorybean.UserService"></property>
<property name="target" ref="userService"></property>
<property name="interceptorNames" value="myAspect"></property>
</bean>
4.测试类
public void func(){
String xmlpath = "bean.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlpath);
UserService userService = (UserService) applicationContext.getBean("proxyService"); //获取的是代理bean
userService.addUser();
}
测试类的运行结果如下:
三、aop编程
由spring自动生成代理,只需要目标类
1.目标类
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("aop add user");
}
}
2.切面类
确定通知,需要实现不同接口,环绕通知 — MethodInterceptor
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("前");
//手动执行目标方法
Object object = methodInvocation.proceed();
System.out.println("后");
return object;
}
}
3.Spring配置
<bean id="userService" class="com.spr.aopdemo.UserServiceImpl"></bean>
<bean id="myAspect" class="com.spr.aopdemo.MyAspect"></bean>
<aop:config >
<aop:pointcut expression="execution(* com.spr.aopdemo.*.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="myAspect" pointcut-ref="myPointCut"/>
</aop:config>
4.测试类
public void func(){
String xmlpath = "bean.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlpath);
UserService userService = (UserService) applicationContext.getBean("userService");
userService.addUser();
}
总结
本篇主要记录了AOP的简单案例,AOP和工厂bean的主要区别其实也就是在Spring的配置上,工厂bean需要创建一个代理bean,并且使用的时候(在测试类中)获取的也是代理,而AOP不需要创建这样的一个代理bean,创建的这个过程是由Spring去完成的,所以AOP是一个全自动的,而工厂bean只能看做是半自动的。