當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring中AOP开发步骤
生活随笔
收集整理的這篇文章主要介紹了
Spring中AOP开发步骤
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
AOP:不是由Spring定義.AOP聯盟的組織定義.Spring中的通知:(增強代碼)前置通知 org.springframework.aop.MethodBeforeAdvice* 在目標方法執行前實施增強后置通知 org.springframework.aop.AfterReturningAdvice* 在目標方法執行后實施增強環繞通知 org.aopalliance.intercept.MethodInterceptor* 在目標方法執行前后實施增強異常拋出通知 org.springframework.aop.ThrowsAdvice* 在方法拋出異常后實施增強
第一步:導入相應jar包.
* spring-aop-3.2.0.RELEASE.jar * com.springsource.org.aopalliance-1.0.0.jar第二步:編寫被代理對象:
* CustomerDao接口 * CustoemrDaoImpl實現類第三步:寫一個類繼承相關Advice的接口:
public class MyBeforeAdvice implements MethodBeforeAdvice{/*** method:執行的方法* args:參數* target:目標對象*/public void before(Method method, Object[] args, Object target)throws Throwable {System.out.println("前置增強...");} }?
第四步:生成代理:(配置生成代理:)
spring是支持配置文件幫我們生成代理的。<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 目標對象 --><bean id="customerDao" class="cn.itcast.aop.dao.CustomerDaoImpl"/><!-- 定義增強對象 --> <bean id="beforeAdvice" class="cn.itcast.aop.advice.MyBeforeAdvice"/> <!-- 使用spring框架生成代理對象 --> <bean id="customerDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <!-- 代理的目標對象 --> <property name="target" ref="customerDao"></property> <!-- 設置實現的接口告訴代理實現的接口跟CustomerDaoImpl實現類實現的接口一樣 --> <property name="proxyInterfaces" value="cn.itcast.aop.dao.CustomerDao"></property> <!-- 增強是通知name="interceptorNames"攔截所有的方法 ? ?value="beforeAdvice" 增強的通知告訴代理對象應該使用前置增強--> <property name="interceptorNames" value="beforeAdvice"></property> </bean></beans>第五步:編寫測試類
利用spring集成junit將我們需要的目標類注入到測試類中
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SpringTest {@Autowired// @Qualifier("customerDao")//注入真實對象@Qualifier("customerDaoProxy")//注入代理對象private CustomerDao customerDao;@Testpublic void test(){customerDao.add();customerDao.delete();customerDao.find();customerDao.update();} }?
總結
以上是生活随笔為你收集整理的Spring中AOP开发步骤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 互联网晚报 | 3月25日 星期五 |
- 下一篇: Spring MVC之@RequestP