AOP基础

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值