Spring aop(实验写法)
2024-10-20 09:31:49
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();
}
}
最新文章
- 深究标准IO的缓存
- XMLPuLL解析
- python 读取并显示图片的两种方法
- spark-sql访问hive的问题记录
- 挂羊头卖狗肉蓄意欺骗读者——谭浩强《C程序设计(第四版)》中所谓的“按照C99”(二)
- 10个你必须掌握的超酷VI命令技巧
- 360 webscan中防注入跨站攻击的核心
- Openssl生成根证书、服务器证书并签核证书
- BZOJ2621 [Usaco2012 Mar]Cows in a Skyscraper
- 【MySQL】SQL语句嵌套1
- [转] Asp.Net 导出 Excel 数据的9种方案
- Xtrabackup每周增量备份脚本程序
- 分布式基础学习(2)分布式计算系统(Map/Reduce)
- dw cs6 trial
- c语言指针应用
- [luogu P2294] [HNOI2005]狡猾的商人
- TLS/SSL简单过程
- debuginfo-install glibc-2.17-157.el7.x86_64
- C#应用视频教程3.1 USB工业相机测试
- makefile之if函数