Spring2(了解Spring的AOP切面编程,必须看的一篇博文!!)

Spring的AOP

(一)什么是AOP切面编程?

  • AOP(Aspect Oriented Programming)为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
  • 举个例子:
    你想给你的网站加上鉴权,对于一些url,你认为不需要鉴权就可以访问;但对于另一些url,你认为需要有特定权限的用户才能访问,如果你没有使用AOP,单纯的面向对象,那你只能在那些url对应的Controller代码里面,一个一个写上鉴权的代码,如果你使用了AOP,对原有代码就毫无入侵性了,这就是AOP的好处了,把和主业务无关的事情,放到代码外面去做。

(二)AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等;
  • 切面(ASPECT):横切关注点被模块化 的特殊对象,它就是一个类。
  • 通知(Advice):切面必须要完成的工作,它就是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知执行的“地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。
    在这里插入图片描述

(三)使用Spring实现AOP

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

通知类型连接点实现接口
前置通知方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice
引介通知类中增新的方法属性org.springframework.aop.IntroductionInterceptor
1.使用Spring的 API 接口实现AOP

1)用AOP需要导入的依赖:

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

2)定义一个接口,接口里面定义四个方法(增删改查):

public interface UserService {

    public void add();

    public void delete();

    public void update();

    public void search();
}

3)定义一个实体类,实现上面的接口,我们在add()方法前后实现操作:

public class UserServiceImpl implements UserService {
    //这里执行前置操作
    public void add(){
        System.out.println("增加用户");
    }
    //这里执行后置操作

    public void delete(){
        System.out.println("删除用户");
    }

    public void update() {
        System.out.println("更新用户");
    }

    public void search(){
        System.out.println("查询用户");
    }
}

4)通过Advice定义横切逻辑,实现AOP:

//前置通知
public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的" + method.getName() + "方法被执行了");
    }
}
//后置通知
public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "的" + method.getName() + "方法,返回了" + o);
    }
}

5)编写配置类,注入bean、编写增强配置类:
(这里的expression表达式即类名的全称)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
        
    <bean id="userService" class="com.chen.service.impl.UserServiceImpl"/>
    <bean id="log" class="com.chen.config.Log"/>
    <bean id="afterlog" class="com.chen.config.AfterLog"/>

<aop:config>
        <aop:pointcut id="pc-userservice" expression="execution(* com.chen.service.impl.UserServiceImpl.*(..))"/>
        <!-- 配置环绕 -->
        <aop:advisor advice-ref="log" pointcut-ref="pc-userservice"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pc-userservice"/>
</aop:config>

</beans>

6)测试类,我们调用add()方法:

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userservice = (UserService) context.getBean("userService");
    userservice.add();
}
/*结果:
com.chen.service.impl.UserServiceImpl的add方法被执行了
增加用户
com.chen.service.impl.UserServiceImpl的add方法,返回了null
*/

我们可以发现切面编程的切入效果,在add()方法执行的前后实现了切面。

2.自定义切面实现AOP

1)自定义一个切面,类中定义两个方法;

public class DiyPointCut {

    public void before(){
        System.out.println("方法执行前");
    }
    public void after(){
        System.out.println("方法执行后");
    }
}

2)编写配置类:

<bean id="diy" class="com.chen.config.DiyPointCut"/>
<!--配置切面:下面的方法来自于切面-->
<aop:config>
        <aop:aspect ref="diy">
            <aop:pointcut id="pc-userservice" expression="execution(* com.chen.service.impl.UserServiceImpl.*(..))"/>
            <aop:after method="after" pointcut-ref="pc-userservice"/>
            <aop:before method="before" pointcut-ref="pc-userservice"/>
        </aop:aspect>
    </aop:config>

3)结果:

/*
方法执行前
增加用户
方法执行后
*/
3.使用注解实现AOP

需在配置中增加<aop:aspectj-autoproxy/>标签,让spring识别注解;
1)注解切面,@Before 前置注解 @After 后置注解 @Around 环绕注解,在注解后面编写execution表达式:

@Aspect
public class AnnotationPointCut {

    @Before("execution(* com.chen.service.impl.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }

    @After("execution(* com.chen.service.impl.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后");
    }

    @Around("execution(* com.chen.service.impl.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");
        //要执行的方法是哪一个
        Signature signature = joinPoint.getSignature();
        System.out.println(signature);
        //执行方法
        Object proceed = joinPoint.proceed(); 
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

3)结果:

/*
环绕前
void com.chen.service.UserService.add()
方法执行前
增加用户
环绕后
null
方法执行后
*/

我们可以发现通过AOP可以实现我们需要的操作,在方法执行前后实现自己的操作。

//下篇再见…谢谢

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值