zoukankan      html  css  js  c++  java
  • Spring aop(实验写法)

    1. 创建通知:定义一个接口 

     

    Public interface Sleepable
    
    {
    
    voidsleep(); 
    
    }
    然后写一个Human类,他实现了这个接口 publicHuman implements Sleepable{ public void sleep() { System.out.println("睡觉中...!"); } }

      

     

    2.编写一个SleepHelper类,它里面包含了睡觉的辅助工作,用AOP术语来说它就应该是通知

    Public class Sleep Helper implements MethodBeforeAdvice,AfterReturningAdvice  {
    
    publicvoidbefore(Method method, Object[] arguments, Object target)throws
    
    Throwable {      
      System.out.println("睡觉前");            
    }
    publicvoidafterReturning(Object rturnValue, Method method, Object[] arguments, Object target)throwsThrowable {   
         System.out.println("睡觉后");            
    }
    }
    

      

    然后在spring配置文件中进行配置:<!-- 被代理目标对象 -->

    <bean id="Human"class="cn.happy.dao.Human"></bean>
    
    <bean id="SleepHelper"class="cn.happy.aop.SleepHelper"></bean>//定义切点的常用的两种方式:1)使用正则表达式 2)使用AspectJ表达式,//这里用正则表达式<!-- 顾问 -->   
    <bean id="BeforAdvisor"class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    <property name="advice" ref="BeforAdvice"></property> <property name="pattern" value=".*l.*g.*">
    </property>
    </bean><!-- 代理对象 -->//ProxyFactoryBean是一个代理,我们可以把它转换为//proxyInterfaces中指定的实现该interface的代理对象
    <bean id="serviceProxy"class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="Human"></property>
    <property name="interceptorNames" value="BeforAdvisor">
    </property> </bean>代理类 publicclassStuTest {publicstaticvoidmain(String[] args)
    {//通过ClassPathXmlApplicationContext实例化Spring的上下文
    ApplicationContext context=newClassPathXmlApplicationContext("applicationContext.xml");
    //通过ApplicationContext的getBean()方法,根据id来获取Bean的实例
    Sleepable s=(Sleepable)context.getBean("Human");
    s.sleep();
    }
    }
    
    

      

  • 相关阅读:
    面向对象六
    面向对象五
    面向对象四
    面向对象三
    面向对象二
    CentOS7下安装Redis4.0
    在亚马逊的EC2环境中创建swap
    centos7安装rabbitmq操作步骤
    在VUE下使用阿里图标
    Centos7-安装telnet服务
  • 原文地址:https://www.cnblogs.com/LiangPF/p/7084805.html
Copyright © 2011-2022 走看看