1. AOP不能取代OOP,它只是OOP的补充和扩展
2. AOP术语
方面 Aspect: 相当于OOP中的类,就是封装用于横插入系统的功能
通知 Advice: 用于横切的代码不能写在方法中,而要写在和方法类似的实体中,称为通知
Jointpoint:连接点:
切入点(Pointcut):
目标(Target):
代理(Proxy):
织入(Weaving)
3. 4种通知(Advice)
前置通知MethodBeforeAdvice,
后置通知AfterReturningAdvice,
环绕通知AroundAdvice,
异常通知ExceptionAdvice
会传入方法名,参数
要拦截的类和方法
public interface MyInterface
{
public String getHello(String name);
public int getRandomInt(int max);
}
public class MyClass implements MyInterface
{
public String getHello(String name)
{
.......
}
public int getRandomInt(int max)
{
......
}
}
4. 拦截方法
public class BeforeAdvice impleemnts MethodBeforeAdvice
{
public void before(Method method, Object[] args, Object target) throws Throwable
{
System.out.println("beforeAdvice:" + target.getClass().getName() +"." + method.getName() + " 参数值:“ + 啊如果是[0]);
if(method.getName().equals("getHello")
{
args[0] = "chao ren";
}
}
}
5. 装配
<bean id="myClass" class="company.MyClass"/>
<bean id="MyClassProxy" class="org.springframework.aop.framework.Proxy.FactoryBean">
<property name="proxyInterfaces">
<list>
<value>company.MyInterface</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>beforeAdvice</value>
<value>afterAdvice</value>
<value>exceptionAdvice</value>
</list>
</property>
<property name="target">
<ref bean="myClass"/>
</property>
</bean>
7. 调用
MyInterface myInterface = (MyInterface) context.getBean("myClassProxy");
myInterface.getHello("bill");
myInterface.getRandomInt(100);
8. Spring AOP 拦截了目标类中的所有方法,而通常只需要拦截部分的方法
NameMatchMethodPointcut , 通过该切入点,可以拦截指定方法
public class Pointcut extends NameMatchMethodPointcut
{
@Override
public boolean matches (Method method, Class targetClass)
{
this.setMappedName("getHello");
this.setMappedName("get*");
return super.matches(method,targetClass);
}
}
装配
<bean id="pointcu" class="mycomoany.Pointcut/>
<bean id="myAdvisor" class="...DefaultPointAdvisor">
<property name="pointcut">
<ref local="pointcut"/>
</property>
<property name="advice">
<ref local="beforeAdvice"/>
</property>
</bean>
<bean id="MyClassProxy" class="org.springframework.aop.framework.Proxy.FactoryBean">
<property name="proxyInterfaces">
<list>
<value>company.MyInterface</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myAdvisor</value>
<value>afterAdvice</value>
<value>aroundAdvice</value>
<value>exceptionAdvice</value>
</list>
</property>
<property name="target">
<ref bean="myClass"/>
</property>
</bean>
9. 使用控制流切入点
更具要调用被拦截方法的类, 调用被拦截方法的方法, 来拦截
ControllFlowPointcut