Spring中的AOP使用

一、AOP术语。

连接点,是指类里面可以被增强的方法。

切入点,是指实际被增强的方法。

通知,是指实际增强的逻辑部分。

通知有5种类型,分别是前置通知,后置通知,环绕通知,异常通知,最终通知。

切面,是指把通知应用到切入点的过程。

切点表达式,execution([权限修饰符][返回类型][类限定名][方法名]([参数列表]))。

例如:

1.对com.yhx.dao.UserDao类中的show方法进行增强。

execution(public void com.yhx.dao.UserDao.show(..))

2.对com.yhx.dao.UserDao类中的所有方法进行增强。

execution(* com.yhx.dao.UserDao.*(..))

3.对com.yhx.dao包及其子包中的类的所有方法进行增强。

execution(* com.yhx.dao.*.*(..))

二、Spring中的AOP使用。

Spring框架集成AspectJ实现AOP操作。

SpringConfig配置类:

//配置类注解
@Configuration
//组件扫描
@ComponentScan(basePackages = {"com.yhx"})
//自动代理
@EnableAspectJAutoProxy
public class SpringConfig{}

UserDao被增强类:

@Component
//被增强类
public class UserDao {
    public void show(){
        System.out.println("show running...");
    }
}

UserDaoProxy增强类:

@Component
//增强类
@Aspect
public class UserDaoProxy {
    //公共切点表达式提取
    @Pointcut(value = "execution(* com.yhx.dao.UserDao.show(..))")
    public void pointDemo(){ }
    //前置通知
    @Before(value = "pointDemo()")
    public void before(){
        System.out.println("before running...");
    }
    //后置通知(有异常,不通知)
    @AfterReturning(value = "pointDemo()")
    public void afterReturning(){
        System.out.println("afterReturning running...");
    }
    //环绕通知
    @Around(value = "pointDemo()")
    public void around(){
        System.out.println("around running...");
    }
    //异常通知(有异常的时候,才进行通知)
    @AfterThrowing(value = "pointDemo()")
    public void afterThrowing(){
        System.out.println("afterThrowing running...");
    }
    //最终通知(无论是否有异常,都通知)
    @After(value = "pointDemo()")
    public void after(){
        System.out.println("after running...");
    }
}

ProxyTest测试类:

public class ProxyTest {
    public static void main(String[] args) {
        ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserDao userDao = app.getBean("userDao", UserDao.class);
        userDao.show();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值