要进行AOP编程,首先我们要在spring的配置文件中引入aop命名空间(约束):
<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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> |
Spring提供了两种切面声明方式,实际工作中我们可以选用其中一种:
• 基于XML配置方式声明切面。
• 基于注解方式声明切面。
这里我先演示XML配置方式声明切面
首先你要了解切入点表达式。这里是几种常用表达式:
下面方法中的..表示:可以包含参数
l execution(* com.yunlian.service.UserService.add(..))某个类下面的add方法
l execution(* com.yunlian.service.UserService.*(..))—某个类的所有方法
l execution(* com.yunlian.service.*.*(..))---service包下面的所有类的所有方法
l execution(* *.*(..))---所有类中的所有方法
一:先创建如下的包结构和配置文件
第一步:建立UserServiceImpl.java类
第二步:建立切面
建立封装横切关注点的切面MyAspectXML.java类:
第三步:spring-config.xml配置文件
注解方式
第一步:开启注解
在spring配置文件中开启AOP注解:
<aop:aspectj-autoproxy/>
第二步:为切面加注解:
为切面类MyAspectAnno加一个注解:@Aspect
第三步:在横切关注点上加注解
在横切关注点上加上对应通知类型的注解,如:
前置通知:@Before、后置通知:@After等。
第四步:测试
注意:1.在注解情况下,如果环绕通知和异常通知同事存在时,异常通知会失效
2.在注解模式中,不仅需要在切面类上使用@Aspect注解,也需要在spring的配置文件中配置切面的bean(或者通过注解的方式创建切面的bean) 我们这里使用的注解方式创建bean .@Aspect注解不是产生bean的,只是用来告诉spring有该注解的类是切面类。