框架学习之spring整合struts2、hibernate-02AOP编程

来源:互联网 发布:java 泛型 t.class 编辑:程序博客网 时间:2024/06/15 22:47

面向切面编程

AOP?

在运行时,动态地将代码切入到类的指定方法、指定位置上的编程思想就是面向切面的编程
1. 连接点(Joinpoint): 程序执行过程中明确的点,如方法的调用或特定的异常被抛出。
2. 切入点(Pointcut): 指定一个通知将被引发的一系列连接点的集合。
3. 通知(Advice): 在特定的连接点,AOP框架执行的动作。
4. spring通过动态代理来实现

AOP的实现和使用

applicationContext.xml配置
1. 在xml中配置切面

<aop:config>            <aop:pointcut expression="execution(* com.bwf.book.dao.impl.*.*(..))" id="daoPointcut"/>            <aop:aspect ref="logAdvice">                <aop:before method="write"  pointcut-ref="daoPointcut" />                               <aop:after-returning method="write2"  returning="rt"  pointcut-ref="daoPointcut" />                <aop:after-throwing method="write3" throwing="ex" pointcut-ref="daoPointcut" />                <aop:after method="write4" pointcut-ref="daoPointcut" />                <aop:around method="write5" pointcut-ref="daoPointcut" />                           </aop:aspect>               </aop:config>

说明:expression表示切面的切入点,logAdvice表示对应实现类的实例,由spring容器提供,method表示在该实现类中的通知,也就是具体的连接点的动作
在实现类中需要加注解:@Component(“logAdvice”)
通知包括有:“before”、“after-returning”、“after-throwing”和“around”;其中round通知类型需要调用proceed方法才会继续执行之后的程序,否则程序就不会再继续往下运行
2. 在类中配置注解完成切面设计
- 创建一个MyAspect类,在类上声明注解:@Aspect
- 在具体的方法(动作)上面声明注解:
@Before(通知类型)+切入点execution(“….”)
或者在一个方法上注解:
@Pointcut(“…”),在需要处理的方法上面直接调用这个方法@Before(“方法名()”)
3. 最后需要在applicationContext.xml文件中配置:

<!-- 在扫描组件类时,将切面实现类也扫描进来 --><context:component-scan base-package="com.bwf.book" >        <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/></context:component-scan><!-- 负责将容器中所有的“切面”(在类的声明上,使用了@Aspect注解的类)进行自动代理生成 --><aop:aspectj-autoproxy />
原创粉丝点击