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采用的就是动态代理的机制去实现的.

  • 相关阅读:
    php 判断字符串是否以某字符串结尾的方法
    且看新手如何快速新站优化(经验+求指导+找喷) 西安
    xml 序列化和反序列化 西安
    反射+xml 序列化 实际应用 西安
    使用自定义文件缓存提升ASP.NET项目性能 西安
    反射的简单应用(记录) 西安
    java web 中的 controller、service、persistence(mapper)、domain 分别是什么作用?
    nodesass 替换为 sass
    github 访问不了 访问 github,修改 hosts 文件方法
    win10 如何使用管理员权限编辑文件
  • 原文地址:https://www.cnblogs.com/xiaoqiqistudy/p/11298817.html
Copyright © 2011-2022 走看看