在使用Spring 2.0 Schema方式的aop实现中,我们的通知,不再需要实现Spring的接口,如:
import org.aspectj.lang.JoinPoint;
// 不需要在实现MethodBeforeAdvise
public class LogBeforeAdvice ... {
public void before(JoinPoint joinPoint)...{
System.out.println("log before service");
}
}
为了使用Spring 2.0基于XML Schema的AOP设置方式,您必须在XML设档的开头加入AOP的names
<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"
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">
加入相应的namespace后,就可以使用spring的aop标签了
<!-- 配置文件Schemal需要改变 -->
< 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"
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" >
<!-- 加入aop名称空间后,就可以使用spring2.0的标签aop了 -->
< bean id ="logBeforeAdvise" class ="AOP2Schema.LogBeforeAdvice" />
< bean id ="helloSpeaker" class ="AOP2Schema.HelloSpeaker" />
< aop:config >
< aop:aspect id ="logging" ref ="logBeforeAdvise" >
< aop:before pointcut ="execution(* AOP2Schema.ISpeaker.* (..))" method ="before" />
</ aop:aspect >
</ aop:config >
</ beans >
服务接口及实现:
public class HelloSpeaker implements ISpeaker ... {
public void speak() ...{
System.out.println("speak");
}
public void say() ...{
System.out.println("say");
}
}
package AOP2Schema;
public interface ISpeaker ... {
public void speak();
public void say();
}
对上面的aop标签解释一下:
首先可以看到,不需要明确声明ProxyFactoryBean了,所有AOP配置是在aop:confg标签中设置的,aop:spect标签定义Aspect的实现,也就是advise
<aop:before>标签表示设置Advice将作为Before Advise,“pointcut”属性定义PointCut表达式,以上定义了三个部:传回值,方法名和参数类型
* 表示任何返回值类型都符合
AOP2Schema.ISpeaker.* 表示ISpeaker接口里的所有方法都复合
(..) 表示任何参数类型声明符合
我们只要在测试代码中直接获取helloSpeaker,spring就可以自动按配置建立代理对象,并调用相应的advise
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring ... {
public static void main(String args[]) throws Exception...{
ApplicationContext ctx=new ClassPathXmlApplicationContext("AOP2Schema/applicationContext.xml");
ISpeaker speaker=(ISpeaker)ctx.getBean("helloSpeaker");
speaker.speak();
speaker.say();
}
}
测试结果:
log before service
speak
log before service
say