读书人

Spring AOP 学习札记-Springle 二代

发布时间: 2012-09-11 10:49:03 作者: rapoo

Spring AOP 学习笔记-Springle 二代

Spring AOP 二代

public class LogBeforeAdvice { public void before(JoinPoint joinPoint) { System.out.println(joinPoint.getSignature().getName()+",start.............LogBeforeAdvice"); }}

<bean id="logBeforeAdvice" ref="logBeforeAdvice"> <aop:pointcut id="LogbeforePointcut" expression="execution(* hello*(..))"/> <aop:before pointcut-ref="LogbeforePointcut" method="before"/> </aop:aspect></aop:config>

public class AopTest { public static void main(String[] args) { BeanFactory factory = new ClassPathXmlApplicationContext( "applicationContext.xml"); IHello bean = (IHello) factory.getBean("IHello"); bean.hello1("AOP1"); bean.hello2("AOP2"); }}

hello1,start.............LogBeforeAdvicehello1,AOP1hello2,start.............LogBeforeAdvicehello2,AOP2

???? 基于Annotation的前置通知

?

@Aspectpublic class LogBeforeAdvice { @Pointcut("execution(* com.edu.cug.IHello.*(..)) ") public void anymethod(){} @Before("anymethod()") public void before(JoinPoint joinPoint) { System.out.println(joinPoint.getSignature().getName() + ",start.............LogBeforeAdvice"); }}

<bean id="IHello" name="code">public class AopTest { public static void main(String[] args) { BeanFactory factory = new ClassPathXmlApplicationContext( "applicationContext.xml"); IHello bean = (IHello) factory.getBean("IHello"); bean.hello1("AOP1"); bean.hello2("AOP2"); }}

hello1,start.............LogBeforeAdvicehello1,AOP1hello2,start.............LogBeforeAdvicehello2,AOP2

可以看到,基于Annotation的AOP设置方式,在XML上几乎不用设置,只要实例化Advice与你的目标对象,接着一切就让Spring自动取得Annotation信息,进行代理对象建立,无须再做任何的设置。这个范例的执行结果和上一个范例是相同的。

Spring的Pointcut定义

?

Execution (modifiers patterns?ret-type-patterndeclaring-type-pattern?name-pattern (param-pattern)throws-pattern?)

它们分别表示存取修饰匹配(modifiers patterns)、返回值类型匹配(ret-type-pattern

)、类限定名匹配(declaring-type-pattern)、方法名称匹配(参数类型匹配)、异常类型匹配(throws-pattern)、有问号的部分,表示可以省略不声明。

???????? 在Spring2.x中,结合@Pointcut的Annotation定义方式,可以让Pointcut在定义上更加容易,定义包含两个部分:Pointcut表示式与Pointcut签名(signature)。

???????? Pointcut定义是,还可以使用&& 、||、 !运算。

????? 使用Spring2.x的新特性实现AOP更加简单、快捷,所以使用Spring2.x或更高的版本能缩短开发周期,性能方面丝毫不逊色以前的AOP支持。

读书人网 >软件架构设计

热点推荐