AOP通過反射機制實現動態代理/IOC依賴注入


功能:

  日志記錄,事務處理

簡單描述:

  把幾個類的共有代碼,抽取到一個切片中,在運行時,動態地將代碼切入到類的指定方法中。

使用方法:

  通過AOP代理,被調用到InvocationHandler類的invoker方法執行
  配置:被代理接口,被代理接口實現類,各類攔截器

代碼實現:

 1 <!-- 配置事務管理器 -->
 2     <bean id="transactionManager"
 3           class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 4         <property name="sessionFactory" ref="sessionFactory"/>
 5     </bean>
 6 
 7     <!-- 配置事務的傳播特性 -->
 8     <tx:advice id="txAdvice" transaction-manager="transactionManager">
 9         <tx:attributes>
10             <tx:method name="*" propagation="REQUIRED"/>
11         </tx:attributes>
12     </tx:advice>
13 
14     <!-- 那些類的哪些方法參與事務 -->
15     <aop:config>
16         <aop:pointcut id="allServiceMethod"
17                       expression="execution(* com.selfpackage.service.*.*(..))"/>
18         <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice"/>
19     </aop:config><!-- 配置事務管理器 -->
20     <bean id="transactionManager"
21           class="org.springframework.orm.hibernate4.HibernateTransactionManager">
22         <property name="sessionFactory" ref="sessionFactory"/>
23     </bean>
24 
25     <!-- 配置事務的傳播特性 -->
26     <tx:advice id="txAdvice" transaction-manager="transactionManager">
27         <tx:attributes>
28             <tx:method name="*" propagation="REQUIRED"/>
29         </tx:attributes>
30     </tx:advice>
31 
32     <!-- 那些類的哪些方法參與事務 -->
33     <aop:config>
34         <aop:pointcut id="allServiceMethod"
35                       expression="execution(* com.selfpackage.service.*.*(..))"/>
36         <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice"/>
37     </aop:config>

 四、IOC

IoC(控制反轉),將類的創建和依賴關系寫在配置文件里,由配置文件注入,實現了松耦合


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM