zoukankan      html  css  js  c++  java
  • spring实现AOP

    一、.默认advisor自动代理生成器(实现前置增强)

        1.编写接口类

    public interface ISomeService {
        public void doSome();
        public void add();
    }
    

     2.实现接口类中的方法

    public class SomeService implements ISomeService {
        public void doSome() {
            System.out.println("code  ok");
        }
    
        public void add() {
            System.out.println("=========log===============");
        }
    }
    

     3.编写增强类

      

    public class MyBeforeAdvice implements MethodBeforeAdvice {
        public void before(Method method, Object[] objects, Object o) throws Throwable {
            System.out.println("执行前置增强");
        }
    }
    

     4.写配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:p="http://www.springframework.org/schema/p"
           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 id="SomeService" class="cn.happy.service.SomeService"></bean>
    
        <!--增强  通知-->
        <bean  id="beforeAdvice" class="cn.happy.service.MyBeforeAdvice"></bean><!--前置增强-->
        
          <!-- 使用名称匹配方法切入点顾问NameMatchMethodPointcutAdvisor-->
     <bean  id="beforeAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
           <!-- <!–顾问 Advisor 包装通知, 那个方法需要增强–>-->
            <property name="advice" ref="beforeAdvice"></property>
            <property name="mappedNames" value="doSome"></property>
        </bean>
    
        <!--默认advisor自动代理生成器  有几个目标方法都会增强,但是只能对顾问自动代理,不能自动代理通知-->
        <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
    
    </beans>
    

     5.测试方法

     

    public class test01 {
        // AspectJ 
        @Test
        public void testAspect(){
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            ISomeService someService= (ISomeService)context.getBean("SomeService");
            someService.add();
            someService.doSome();
        }
    

     6.测试结果

  • 相关阅读:
    <<Rust程序设计语言>>个人版(4: 所有权)
    《逻辑学入门》笔记(45-66)
    《逻辑学入门》笔记(23-44)
    <<Rust程序设计语言>>个人版(3.3: 函数/3.4: 注释/3.5: 控制流)
    <<Rust程序设计语言>>个人版(1: 入门/2: 编写猜谜游戏)
    网站如何保护用户的密码
    在 Gin 项目中使用 WebSocket
    《逻辑学入门》笔记(1-22)
    浅谈双重认证逻辑
    某大型网络安全活动中遇到的钓鱼邮件
  • 原文地址:https://www.cnblogs.com/cn-930621/p/7657715.html
Copyright © 2011-2022 走看看