Spring中的Advice类型及其应用
在Spring中,Advice都是通过Interceptor来实现的,主要有以下几种:
1. 环绕Advice:
//例子摘自Spring referencepublic interface MethodInterceptor extends Interceptor {环绕advice类似一个拦截器链,这个拦截器链的中心就是被拦截的方法。在程序(1)(2)我们可以加入我们自己的代码,以表示在方法执行前后我们需要干什么。invocation.proceed()方法运行指向连接点的拦截器链并返回proceed()的结果。
2. Before Advice
public interface MethodBeforeAdvice extends BeforeAdvice { 一个更简单的通知类型是<?xml version="1.0" encoding="UTF-8"?><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.0.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="loginServiceTarget"
class="com.learn.spring.test.advisor.LoginServiceImpl"/>
<bean id="loginNameCheckInterceptor"
class="com.learn.spring.test.advisor.LoginNameCheckInterceptor"/>
<!--
<bean id="loginCheckInterceptor"
class="com.learn.spring.test.advisor.LoginCheckInterceptor"/>
-->
<bean id="loginCountInterceptor"
class="com.learn.spring.test.advisor.LoginCountInterceptor"/>
<bean id="exceptionThrowInterceptor"
class="com.learn.spring.test.advisor.ExceptionThrowInterceptor"/>
<bean id="loginService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target"><ref local="loginServiceTarget"/></property>
<property name="proxyInterfaces">
<list>
<value>com.learn.spring.test.advisor.LoginService</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>loginNameCheckInterceptor</value>
<value>loginCountInterceptor</value>
<value>exceptionThrowInterceptor</value>
</list>
</property>
</bean>
</beans>
测试代码运行:
public class Test {输出结果:
check user's name is valid?