实现AOP的三种方法(使用SpringAPI,自定义类,注解)

什么是AOP

AOP(Aspect Oriented Programming)是面向对象的延续,意思是面向切面编程,可以通过预编译方式和运行期动态代理实现在不修改原码的情况下给程序动态统一添加功能的一种技术,AOP其实也是在不断的实现解耦。

我们在做一些业务,如:日志,事务,安全等都会写在业务代码中,有时候这些代码会重复,维护非常的不便,AOP实现了把这些业务需求与系统需求分开来做,这种解决方式也是一种代理机制
AOP在Spring中的作用
提供声明的事务:允许用户自定义切面
切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。

通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(Target):被通知对象。

代理(Proxy):向目标对象应用通知之后创建的对象。

切入点(PointCut):切面通知 执行的 “地点”的定义。

连接点(JointPoint):与切入点匹配的执行点。

AOP逻辑关系图:
在这里插入图片描述

使用SpringAPI实现AOP

编写业务类:
接口:

package com.wang.service;

public interface UserService {
    public void add();

    public void delete();

    public void update();
    public void query();
}

实现类:

package com.wang.service;

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 query() {
        System.out.println("查询用户");
    }
}

定义日志增加类实现

mport org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {

    //method:要执行的目标对象的方法
    //objects:要被调用的方法的参数
    //o:目标对象
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"的"+method.getName()+"执行了");
    }
}

执行后的日志:

package com.wang.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    //returnValue:返回值
    //method:被调用的方法
    //args:被调用的方法对象的参数
    //target:被调用的目标对象

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+target.getClass().getName()
        +"的"+method.getName()+"方法"
        +"返回值"+returnValue);
    }
}

编写Spring核心配置文件
【导入约束】

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       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">

    <!--注册bean-->
    <bean id="userService" class="com.wang.service.UserServiceImpl"/>

    <!--注册日志类的bean-->
    <bean id="log" class="com.wang.log.Log"/>
    <bean id="afterLog" class="com.wang.log.AfterLog"/>

    <!--&lt;!&ndash;使用spring的aop切入-->
   <!--1.导入约束:-->
       <!--xmlns:aop="http://www.springframework.org/schema/aop"-->
       <!--http://www.springframework.org/schema/aop-->
       <!--http://www.springframework.org/schema/aop/spring-aop.xsd-->
   <!--2.aop:config-->

    <aop:config>
        <!--切入点
        expression表达式,表示要切入的位置
        语法:execution([类的修饰符] [类的全路径] [方法] [参数])

        -->
        <aop:pointcut id="pointcut" expression
                ="execution(* com.wang.service.UserServiceImpl.*(..))"/>
        <!--执行通知-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>

</beans>

测试类:
这个需要导入aop的组织入包
https://mvnrepository.com/artifact/org.aspectj/aspectjweaver/1.8.9

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

编写测试类:

 @Test
    public void test(){
        ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml");
     UserService userService = (UserService) Context.getBean("userService");
               /*
        问题:报错,没有aspectjweaver包
        使用aop需导入一个包
                <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>


        问题:spring调用的是真实对象userService
        暗箱中: 动态的修改userService,在方法的前后或者其他通知的地方增加了我们的切入代码。
        我们就可以实现依旧调用原来的对象,产生增加新的业务的功能;

         */
               userService.add();

    }

2.自定义类实现AOP

1.自定义一个类,写入两个方法


public class Diy {

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

2.注入bean

<!--自定义的AOP增强类-->
<bean id="diy" class="com.kuang.diy.Diy"/>

3.使用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"

       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">
   <!--注册bean对象-->
    <bean id="userService" class="com.wang.service.UserServiceImpl"/>

    <!--自定义AOP增强类-->
    <bean id="diy" class="com.wang.diy.Diy"/>

    <!--编写aop配置文件-->
    <aop:config>
        <!--切面-->
        <aop:aspect ref="diy">
            <aop:pointcut id="diyPointCut" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
           <aop:before method="before" pointcut-ref="diyPointCut"/>
            <aop:after method="after" pointcut-ref="diyPointCut"/>
        </aop:aspect>
    </aop:config>


</beans>

4.测试类
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);

  UserService userService=(UserService)context.getBean("userService");
  userService.add();

}

5.运行结果
在这里插入图片描述

使用注解实现AOP

1.目标对象不变
2.编写增强的类,写注解

  • 注意点:需要将类注解为切面
  • 方法上就是切入点,增强
@Aspect
public class Anno {

    //切入点可以直接写到增强上面
    @Before("execution(* com.wang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=============方法执行前=============");
    }
    @After("execution(* com.wang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===============方法执行后=========");
    }

    @Around("execution(* com.wang.service.UserServiceImpl.*(..))")
   public void around(ProceedingJoinPoint jp) throws Throwable {
       System.out.println("环绕前");
       System.out.println("签名"+jp.getSignature());//获得执行切入点

       //执行目标方法
       Object proceed = jp.proceed();

       System.out.println("环绕后");

       System.out.println(proceed);
   }
}

4.配置文件

<?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"
       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">
    <!--注册bean对象-->
    <bean id="userService" class="com.wang.service.UserServiceImpl"/>

    <!--注解实现AOP的类-->
    <bean id="anno" class="com.wang.anno.Anno"/>

    <!--识别注解,自动代理-->
    <aop:aspectj-autoproxy/>


    </beans>

5.测试类

   @Test
    public void tset3(){
      ApplicationContext context = new ClassPathXmlApplicationContext("anno.xml");
      UserService userService=(UserService)context.getBean("userService");

      userService.add();

    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值