java - spring - AOP

AOP: 面向切面编程(Aspect oriented Programming)

说白了就是把常用业务方法打包,在放在需要的位置。这个和OOP(面向对象)是不冲突的,只是为了完善面向对象编程中的一些业务逻辑问题。

比如:

A在运行的时候,打印日志。

B在运行的时候,打印日志。

传统方法:

A运行结束位置写一个log方法。

B运行结束位置写一个log方法。

这样万一是个大项目,有100方法都需要打印日志。万一有改动(比如客户要求改打印格式),全部修改一遍工作量很大。

所以为了解决这个问题,有了AOP编程思想。

因为打印log的方法是基本通用的,所以可以专门写一个方法集中管理。然后所有目标的方法执行的时候统一调用这里的方法。把方法分配到需要的位置。

Spring的AOP主要就是干这个的。

步骤:

1.  添加一个用类,集合了需要的方法

2. 添加spring的注解(我这里是@Component),交给spring组建管理

3. 添加aspect注解,表示这个是用来aop的类

4. 添加对应注解和表达式用来告诉spring这些方法是在哪些类的什么时候使用

5. 添加配置文件,开启AOP模式

java:

package com.itheima.service;



import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import com.itheima.domain.Account;

@Component
@Aspect
public class AopTest {


    //* * com.itheima.service.AccountService.*(..)  返回任意权限,任意返回类型,的这个类中的任意方法,参数可以是任意。根据具体需求修改

    //@Before("execution(public void com.itheima.service.AccountService.aopTest())")   //在AccountService类的aopTest运行前,运行该方法
    @Before("execution(public * com.itheima.service.serviceImpl.AccountServiceImpl.findAll())")//在AccountServiceImpl类的findAll运行前,运行该方法
    public void beforeShowData(){
        System.out.println("findAll目标方法准备运行");
    }

    @After("execution(public void com.itheima.service.AccountService.aopTest())")   //在AccountService类的aopTest运行后,都运行该方法
    public void afterShowData(){
        System.out.println("目标方法运行了");
    }

    @AfterReturning("execution(public void com.itheima.service.AccountService.aopTest())")   //在AccountService类的aopTest正常结束后,运行该方法
    public void afterReturnShowData(){
        System.out.println("目标方法返回了");
    }

    @AfterThrowing("execution(public void com.itheima.service.AccountService.aopTest())")   //在AccountService类的aopTest抛出异常时,运行该方法
    public void afterThrowData(){
        System.out.println("目标方法抛出异常");
    }
}

配置文件中添加:

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

猜你喜欢

转载自www.cnblogs.com/clamp7724/p/11922469.html
今日推荐