Spring学习总结(三)---基于注解的AOP开发

在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。主要用于日志记录,性能统计,安全控制,事务处理,异常处理等等。

步骤

  1. 创建目标接口和目标类
public interface TargetInterface {
    void save();
    void run(int i);
}
@Component("target")
public class Target implements TargetInterface {

    @Override
    public void save() {
        System.out.println("save running ...");
    }

    @Override
    public void run(int i) {
        i = 1/0;
        System.out.println("running ...");
    }
}
  1. 创建切面类
@Component("myAspect")
@Aspect //标注当前类是切面
public class MyAspet {
    @Before("execution(* com.littlepants.anno.*.*(..))")
    public void before(){
        System.out.println("前置增强....");
    }
    
    public void after(){
        System.out.println("后置增强...");
    }
    
    public Object around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("before");
        Object proceed = point.proceed();//切点方法
        System.out.println("after");
        return proceed;
    }
    
    public void afterThrowing(){
        System.out.println("异常抛出");
    }
}
  1. 将目标类和切面类的对象创建权交给Spring
@Component("target")
  1. 在切面类中使用注解配置织入关系
@Aspect
  1. 在配置文件中开启组件扫描和AOP自动代理
<?xml version="1.0" encoding="UTF-8"?>
<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: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/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">

    <context:component-scan base-package="com.littlepants.anno"></context:component-scan>

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

注解通知的类型

名称注解备注
前置@Before方法在切入点方法之前执行
后置@AfterReturning方法在切入点方法之后执行
环绕@Around方法在切入点方法之前和之后均执行
异常抛出@AfterThrowing方法在异常抛出后执行
最终@After类似于finally,无论是否有异常均执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值