Spring学习2-AOP

AOP的使用
1.需要引入aspectJ的jar包。

在这里插入图片描述
2.在配置文件中 配置自动扫描和aop自动代理

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
 <!-- 在配置文件中配置组件扫描 -->
 <context:component-scan base-package="com.test" />
<!-- 在配置文件中配置aop自动代理 -->
 <aop:aspectj-autoproxy />  
</beans>

3.定义切面

@Component
@Aspect  //定义切面
public class Broker {
//   前置通知
//   当执行到响应的代码的时候,就会触发切面中的代码  @Before表示在相应方法之前执行。
 @Before("execution(public void signContract())")
 public void look() {
      System.out.println("看看");
 }
//   后置通知
 @After(value = "execution(public * *(..))")
 public void live() {
      System.out.println("住住");
 }
}


@Component
@Aspect  //定义切面
public class Broker {
    //环绕通知
 @Around("execution(public void signContract())")
 public void around(ProceedingJoinPoint joinPoint) {
      
      System.out.println("啦啦啦  ");
      
      try {
//            可以控制 被拦截的方法 执不执行,执行的顺序
          joinPoint.proceed();
      } catch (Throwable e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      
 }
}

4.相应的语法
在通知中通过value属性定义切点

•通过execution函数,可以定义切点的方法切入

•语法:
–execution(<访问修饰符>?<返回类型><方法名>(<参数>)<异常>)

•例如

–匹配所有类public方法   execution(public * *(..))

–匹配指定包下所有类方法   execution(* com.imooc.dao.*(..))

-不包含子包–execution(* com.imooc.dao..*(..))  ..*表示包、子孙包下所有类

–匹配指定类所有方法   execution(* com.imooc.service.UserService.*(..))

–匹配实现特定接口所有类方法    execution(* com.imooc.dao.GenericDAO+.*(..))

–匹配所有save开头的方法   execution(* save*(..))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值