您的位置:首页 > 编程语言 > Java开发

Spring 切面 AOP基础 之二

2015-05-03 21:36 281 查看
锋利的AOP,上回说到我们利用AOP对服务进行了代理,切的很亮,很光滑,我想吟一手,快拦住我。莫道男儿心如铁,君不见,满川红叶,尽是离人眼中血。

对于AOP还应该罅隙的解释一下,切面的功能被称为通知Advice。通知:描述切面要完成的工作,确定何时何地执行。

连接点(Joinpint):程序执行中能够插入切面的一个时机,可以是方法被调用时,异常抛出时,切面代码通过这个点插入到程序的一般流程中。

切入点(Pointcut):切入点可以缩小切面通知的连接点的范围。相当于切入点定义了“何地”,通常使用明确的类和方法名称,或者利用正则匹配类和方法的名称模板。

切面(Aspect):切面是通知和切入点的结合。

接上文的例子,这次使用Pointcut来使用AOP:

spring配置文件:Spring-Custom.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 
<bean id="customerService" class="com.mkyong.customer.services.CustomerService" >
<property name="name" value="Yong Mook Kim" />
<property name="url" value="http://www.mkyong.com" />
</bean>

<bean id="hijackAroundMethodBeanAdvice" class="com.mkyong.aop.HijackAroundMethod" />

<!--代理类,代理Service同时注入AOP的切点  -->
<bean id="customerServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">

<property name="target" ref="customerService" />

<property name="interceptorNames">
<list>
<value>customerAdvisor</value>
</list>
</property>
</bean>

<!--<bean id="customerAdvisor"
class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="mappedName" value="printName" />
<property name="advice" ref="hijackAroundMethodBeanAdvice" />
</bean>-->

<!--通知接入点  -->
<bean id="customerAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="patterns">
<list>
<value>.*URL.*</value>
</list>
</property>

<property name="advice" ref="hijackAroundMethodBeanAdvice" />
</bean>

</beans>


这样就利用了切入点定义了包含URL的路径才会被执行通知。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: