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

  

 

转载于:https://www.cnblogs.com/LiangPF/p/7084805.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值