• 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();
    }
    }
    
    

      

  • 相关阅读:
    Json的转换
    Object类型的转为String类型
    如何获取实体类中的属性和属性值
    Collections.sort 的日期排序
    idea 报错 :error:java:Compilation failed:internal java compiler error
    System.nanoTime与System.currentTimeMillis比较
    Java中instanceof和isInstance区别详解
    避免实例化特有工具类
    加载Properties文件工具类:LoadConfig
    详解SVN 的使用
  • 原文地址:https://www.cnblogs.com/LiangPF/p/7084805.html
Copyright © 2020-2023  润新知