快速入门
六个步骤:
①导入 AOP 相关坐标
<!--导入spring的context坐标,context依赖aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- aspectj的织入 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
②创建目标接口和目标类(内部有切点)
public interface TargetInterface {
void save();
}
---------------------------------------------------------------------------
public class Target implements TargetInterface {
public void save() {
System.out.println("iu给我布置了科学家不错");
}
}
③创建切面类(内部有增强方法)
public class MyAspect {
public void before(){
System.out.println("前置增强。。。。");
}
}
④将目标类和切面类的对象创建权交给 spring
<!--目标对象-->
<bean id="target" class="com.trc.aop.Target"/>
<!--切面对象-->
<bean id="myAspect" class="com.trc.aop.MyAspect"/>
⑤在 applicationContext.xml 中配置织入关系
<!--配置织入:告诉spring哪些方法(切点)需要进行哪些增强-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--抽取切入点表达式-->
<aop:pointcut id="pointCut" expression="execution(* com.trc.aop.*.*(..))"/>
<!--切面:切点+通知-->
<!--<aop:before method="before" pointcut="execution(public void com.trc.aop.Target.save())"/>-->
<!--<aop:before method="before" pointcut="execution(* com.trc.aop.*.*(..))"/>-->
<aop:before method="before" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
⑥测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
xml的命名空间加入
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
"
XML 配置 AOP 详解
- 切点表达式的写法
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
-
访问修饰符可以省略
-
返回值类型、包名、类名、方法名可以使用星号* 代表任意
-
包名与类名之间一个点 . 代表当前包下的类,两个点 … 表示当前包及其子包下的类
-
参数列表可以使用两个点 … 表示任意个数,任意类型的参数列表
例如:
execution(public void com.itheima.aop.Target.method())
execution(void com.itheima.aop.Target.*(..))
execution(* com.itheima.aop.*.*(..))
execution(* com.itheima.aop..*.*(..))
execution(* *..*.*(..))
- 通知的类型
通知的配置语法:
<aop:通知类型 method=“切面类中方法名” pointcut=“切点表达式"></aop:通知类型>
- 切点表达式的抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替 pointcut 属性来引用抽取后的切点表达式。
<aop:config>
<!--引用myAspect的Bean为切面对象-->
<aop:aspect ref="myAspect">
<aop:pointcut id="myPointcut" expression="execution(* com.itheima.aop.*.*(..))"/>
<aop:before method="before" pointcut-ref="myPointcut"></aop:before>
</aop:aspect>
</aop:config>
知识要点
- aop织入的配置
<aop:config>
<aop:aspect ref=“切面类”>
<aop:before method=“通知方法名称” pointcut=“切点表达式"></aop:before>
</aop:aspect>
</aop:config>
- 通知的类型:前置通知、后置通知、环绕通知、异常抛出通知、最终通知