实现AOP的三种方式

本文详细介绍了AOP(面向切面编程)的概念,及其在Spring框架中的重要作用,如提供声明性事务和自定义切面。通过示例展示了使用Spring API、自定义类和注解三种方式实现AOP,包括前置和后置通知的添加,降低了业务逻辑间的耦合度,提高了代码的可重用性和开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念

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

AOP在Spring中的作用

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

使用Spring实现AOP

1. 导入一个包

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

2. 实现方式

2.1 方式一:使用Spring的API接口
  1. 接口
    public interface IUserService {
        void add();
        void delete();
        void update();
        void query();
    }
  1. 实现类
    public class UserServiceImpl implements IUserService {
        public void add() {
            System.out.println("增加一个用户");
        }
    
        public void delete() {
            System.out.println("删除一个用户");
    
        }
    
        public void update() {
            System.out.println("修改一个用户");
    
        }
    
        public void query() {
            System.out.println("查询一个用户");
    
        }
    }
  1. 前置log
    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()+"被执行了");
        }
    }
  1. 后置log
    public class AfterLog implements AfterReturningAdvice {
        //o:返回结果
        //method:方法
        //objects:参数
        //o1:目标对象
        public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
            System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
        }
    }
  1. xml文件
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           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
           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.kuang.service.UserServiceImpl"/>
        <bean id="log" class="com.kuang.log.Log"/>
        <bean id="afterLog" class="com.kuang.log.AfterLog"/>
        <!--方式一:使用原生spring api接口-->
        <!--配置aop:需要导入aop约束-->
        <aop:config>
            <!--切入点:expression表达式(固定写法,要执行的位置:修饰词,返回值,列名,方法名,参数)-->
            <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
            <!--执行环绕增加-->
            <!--把log类切入到方法pointcut里-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        </aop:config>
    </beans>
  1. MyTest文件
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            /*动态代理代理的是接口*/
            IUserService userService = context.getBean("userService", IUserService.class);
            userService.add();
        }
    }
2.2 使用自定义类来实现AOP
  1. 接口
    public interface IUserService {
        void add();
    }
  1. 实现类
    public class UserServiceImpl implements IUserService {
        public void add() {
        System.out.println("实现了add方法");
        }
    }
  1. 自定义类
    public class DiyPointCut {
        public void before(){
            System.out.println("我是猪!");
        }
        public void after(){
            System.out.println("你也是猪!");
        }
    }
  1. xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           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
           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.kuang.service.UserServiceImpl"/>
        
        <!--方式二:自定义类-->
        <bean id="diyPointCut" class="com.kuang.diy.DiyPointCut"/>
        <aop:config>
            <!--自定义切面,ref需要引用的类-->
            <aop:aspect ref="diyPointCut">
                <!--切入点-->
                <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
                <!--通知-->
                <aop:before method="before" pointcut-ref="pointcut"/>
                <aop:after method="after" pointcut-ref="pointcut"/>
            </aop:aspect>
        </aop:config>
    </beans>
  1. 测试方法
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            IUserService userService = context.getBean("userService", IUserService.class);
            userService.add();
        }
    }
    <!--
        测试结果:
            我是猪!
            实现了add方法
            你也是猪!
    -->
2.3 使用注解实现AOP
  1. 接口
    public interface IUserService {
        void add();
    }
  1. 实现类
    public class UserServiceImpl implements IUserService {
        public void add() {
        System.out.println("实现了add方法");
        }
    }
  1. 注解类
/*使用注解实现AOP*/
    @Aspect/*标记为注解*/
    public class AnnotationPointcut {
        @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("方法执行前");
        }
        @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("方法执行后");
        }
    }
  1. xml类
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           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
           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.kuang.service.UserServiceImpl"/>
        <!--注入bean-->
        <bean id="annotation" class="com.kuang.diy.AnnotationPointcut"/>
        <!--开启注解支持-->
        <aop:aspectj-autoproxy/>
</beans>
  1. MyTest
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            IUserService userService = context.getBean("userService", IUserService.class);
            userService.add();
        }
    }
    <!--
        运行结果:
            方法执行前
            实现了add方法
            方法执行后
    -->

概念

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

AOP在Spring中的作用

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

使用Spring实现AOP

1. 导入一个包

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

2. 实现方式

2.1 方式一:使用Spring的API接口
  1. 接口
    public interface IUserService {
        void add();
        void delete();
        void update();
        void query();
    }
  1. 实现类
    public class UserServiceImpl implements IUserService {
        public void add() {
            System.out.println("增加一个用户");
        }
    
        public void delete() {
            System.out.println("删除一个用户");
    
        }
    
        public void update() {
            System.out.println("修改一个用户");
    
        }
    
        public void query() {
            System.out.println("查询一个用户");
    
        }
    }
  1. 前置log
    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()+"被执行了");
        }
    }
  1. 后置log
    public class AfterLog implements AfterReturningAdvice {
        //o:返回结果
        //method:方法
        //objects:参数
        //o1:目标对象
        public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
            System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
        }
    }
  1. xml文件
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           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
           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.kuang.service.UserServiceImpl"/>
        <bean id="log" class="com.kuang.log.Log"/>
        <bean id="afterLog" class="com.kuang.log.AfterLog"/>
        <!--方式一:使用原生spring api接口-->
        <!--配置aop:需要导入aop约束-->
        <aop:config>
            <!--切入点:expression表达式(固定写法,要执行的位置:修饰词,返回值,列名,方法名,参数)-->
            <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
            <!--执行环绕增加-->
            <!--把log类切入到方法pointcut里-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        </aop:config>
    </beans>
  1. MyTest文件
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            /*动态代理代理的是接口*/
            IUserService userService = context.getBean("userService", IUserService.class);
            userService.add();
        }
    }
2.2 使用自定义类来实现AOP
  1. 接口
    public interface IUserService {
        void add();
    }
  1. 实现类
    public class UserServiceImpl implements IUserService {
        public void add() {
        System.out.println("实现了add方法");
        }
    }
  1. 自定义类
    public class DiyPointCut {
        public void before(){
            System.out.println("我是猪!");
        }
        public void after(){
            System.out.println("你也是猪!");
        }
    }
  1. xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           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
           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.kuang.service.UserServiceImpl"/>
        
        <!--方式二:自定义类-->
        <bean id="diyPointCut" class="com.kuang.diy.DiyPointCut"/>
        <aop:config>
            <!--自定义切面,ref需要引用的类-->
            <aop:aspect ref="diyPointCut">
                <!--切入点-->
                <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
                <!--通知-->
                <aop:before method="before" pointcut-ref="pointcut"/>
                <aop:after method="after" pointcut-ref="pointcut"/>
            </aop:aspect>
        </aop:config>
    </beans>
  1. 测试方法
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            IUserService userService = context.getBean("userService", IUserService.class);
            userService.add();
        }
    }
    <!--
        测试结果:
            我是猪!
            实现了add方法
            你也是猪!
    -->
2.3 使用注解实现AOP
  1. 接口
    public interface IUserService {
        void add();
    }
  1. 实现类
    public class UserServiceImpl implements IUserService {
        public void add() {
        System.out.println("实现了add方法");
        }
    }
  1. 注解类
/*使用注解实现AOP*/
    @Aspect/*标记为注解*/
    public class AnnotationPointcut {
        @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("方法执行前");
        }
        @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("方法执行后");
        }
    }
  1. xml类
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           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
           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.kuang.service.UserServiceImpl"/>
        <!--注入bean-->
        <bean id="annotation" class="com.kuang.diy.AnnotationPointcut"/>
        <!--开启注解支持-->
        <aop:aspectj-autoproxy/>
</beans>
  1. MyTest
    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            IUserService userService = context.getBean("userService", IUserService.class);
            userService.add();
        }
    }
    <!--
        运行结果:
            方法执行前
            实现了add方法
            方法执行后
    -->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值