Spring AOP功能的实现

 2023-09-08 阅读 22 评论 0

摘要:主要有两种方式:一种是基于XML Schema的设置,一种是基于Annotation的支持 基于XML Schema的前置通知(现在LogBeforeAdvice不需要实现MethodBeforeAdvice) LogBeforeAdvice.java public class LogBeforeAdvice {public void before(JoinPoint join

主要有两种方式:一种是基于XML Schema的设置,一种是基于Annotation的支持

基于XML Schema的前置通知(现在LogBeforeAdvice不需要实现MethodBeforeAdvice)

LogBeforeAdvice.java
public class LogBeforeAdvice {public void before(JoinPoint joinPoint) {System.out.println(joinPoint.getSignature().getName()+",start.............LogBeforeAdvice");}
}
applicationContext.xml
<bean id="logBeforeAdvice" class="com.edu.cug.LogBeforeAdvice"></bean><aop:config><aop:aspect id="logBeforeAspect" ref="logBeforeAdvice"><aop:pointcut id="LogbeforePointcut" expression="execution(* hello*(..))"/><aop:before pointcut-ref="LogbeforePointcut" method="before"/></aop:aspect></aop:config>

spring的主要功能是什么、测试程序:

View 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.............LogBeforeAdvice
hello1,AOP1
hello2,start.............LogBeforeAdvice
hello2,AOP2
  • 基于Annotation的前置通知
  • 定义切面:
    LogBeforeAdvice.java
    @Aspect
    public 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");}
    }
    applicationContext.xml
    <bean id="IHello" class="com.edu.cug.IHelloImpl"></bean><bean id="logBeforeAdvice" class="com.edu.cug.LogBeforeAdvice"></bean><aop:aspectj-autoproxy/>

    测试程序

    AopTest.java
    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");}
    }

    Spring的核心。测试结果

    hello1,start.............LogBeforeAdvice
    hello1,AOP1
    hello2,start.............LogBeforeAdvice
    hello2,AOP2

    在Spring2.x中要声明Pointcut,主要包括两个部分:Pointcut表达式(expression)与Pointcut签名(signature)


转载于:https://www.cnblogs.com/azai/archive/2012/09/17/2688114.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/20178.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息