spring AOP实现——xml方法
生活随笔
收集整理的這篇文章主要介紹了
spring AOP实现——xml方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
上一文中 講了Annotation如何配置AOP,地址如下:http://5148737.blog.51cto.com/5138737/1428048
使用同樣的bean,用xml來實(shí)現(xiàn)一下:
Hello.java 接口
定義了三個(gè)方法:
package?com.xj.bean.aop;public?interface?Hello?{public?void?addHello();???//添加方法public?void?deleteHello();??//刪除方法public?void?findHello(); }2.HelloImpl.java實(shí)現(xiàn)類
實(shí)現(xiàn)了接口中的三個(gè)方法,簡單的打印
package?com.xj.bean.aop; public?class?HelloImpl?implements?Hello{@Overridepublic?void?addHello()?{System.out.println("add");}@Overridepublic?void?deleteHello()?{System.out.println("delete");}@Overridepublic?void?findHello()?{System.out.println("find");}}3.HelloProxy.java(所謂的Aspect)
不再使用annotation,所以注解去掉,里面的兩個(gè)校驗(yàn)方法,在執(zhí)行之前打印日志,執(zhí)行之后打印日志。
package?com.xj.bean.aop;public?class?HelloProxy?{//準(zhǔn)備在每個(gè)方法執(zhí)行之前打印日志private?void?beforeLog(){????System.out.println("check?add");???? }//準(zhǔn)備在每個(gè)方法執(zhí)行之后打印日志private?void?afterLog(){System.out.println("after?check?delete");} }4.ApplicationContext.xml
<?xml?version="1.0"?encoding="UTF-8"??>??? <beans?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??xmlns="http://www.springframework.org/schema/beans"??xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans??http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/aop?http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">???<!--?<aop:aspectj-autoproxy/>?xml方法不需要開啟aspectj的注解-->?<bean?id="hello"?class="com.xj.bean.aop.HelloImpl"/>??<!--定義普通的bean--><bean?id="helloProxy"?class="com.xj.bean.aop.HelloProxy"/>??<!--定義Aspect的bean--><!--Aop的xml配置,均采用aop:開頭,并且都方法aop:config中--><aop:config><!--?定義aspect,ref引用所在的bean--><aop:aspect??ref="helloProxy">???<!--定義pointcut:即特殊功能的執(zhí)行范圍--><aop:pointcut?id="addMethod"?expression="execution(*?com.xj.bean.aop.*.add*(..))"/><aop:pointcut?id="deleteMethod"?expression="execution(*?com.xj.bean.aop.*.delete*(..))"/><!--?定義advice,即執(zhí)行時(shí)機(jī),為after、before、throwing等--><aop:before?method="beforeLog"?pointcut-ref="addMethod"/><aop:after?method="afterLog"?pointcut-ref="deleteMethod"/></aop:aspect></aop:config></beans>5.測試
ApplicationContext?context?=new?ClassPathXmlApplicationContext("applicationContext.xml"); Hello?hello?=?(Hello)context.getBean("hello"); hello.addHello(); hello.deleteHello();6.結(jié)果
可以看出來,結(jié)果和annotation相同。
before?check?add?????//add方法之前打印日志 add delete after?check?delete????//delete方法之后打印日志轉(zhuǎn)載于:https://blog.51cto.com/5148737/1428071
總結(jié)
以上是生活随笔為你收集整理的spring AOP实现——xml方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android之个性化ListView实
- 下一篇: cs时间校准