zoukankan      html  css  js  c++  java
  • Spring-自定义类实现AOP(八)

    使用Spring的API实现的AOP需要实现API中的一些接口重写其中的方法,看起来有点复杂需要我们好好的去推敲.

    我们自定义的实现AOP变得更加简单.

    自定一个Aop增强类:也就是所谓的切面

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

    逻辑业务层

    public interface UserService {
    
         void add();
         void delete();
         void update();
         void query();
    
    }

    逻辑业务层的实现类

    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("查询了一个用户");
        }
    }

    配置Springh核心配置文件

    <?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="org.west.service.UserServiceImpl"/>
    
        <bean id="diy" class="org.west.diy.Diy"/>
    
        <!--编写AOP配置文件-->
    
        <aop:config>
            <!--切面-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="diyPointCut" expression="execution(* org.west.service.UserServiceImpl.*(..))"/>
        <aop:before method="before" pointcut-ref="diyPointCut"/>
        <aop:after method="after" pointcut-ref="diyPointCut"/>
    </aop:aspect>
    
        </aop:config>
    
    
    </beans>

    测试类

    public class TestDemo {
        @Test
        public void test(){
    
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    
            UserService userService = (UserService) context.getBean("userService");
    
            userService.add();
    
        }
    
    
    
    }

    测试结果:

    ------->在方法执行前
    增加了一个用户
    ------->在方法执行后

    我们可以观察到在没有改变业务逻的功能下我们可以在程序中动态的去插入一些功能.AOP采用的就是动态代理的机制去实现的.

  • 相关阅读:
    面向对象中一些容易混淆的概念
    day12作业
    day10作业
    day09作业
    Where与Having的区别
    排序算法之快速排序
    排序算法之冒泡排序
    jQuery中的100个技巧
    用node.js给图片加水印
    代码高亮美化插件-----SyntaxHighlighter
  • 原文地址:https://www.cnblogs.com/xiaoqiqistudy/p/11298817.html
Copyright © 2011-2022 走看看