xml方式实现aop-快速入门
生活随笔
收集整理的這篇文章主要介紹了
xml方式实现aop-快速入门
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于 XML 的 AOP 開發
快速入門
①導入 AOP 相關坐標
②創建目標接口和目標類(內部有切點)
③創建切面類(內部有增強方法)
④將目標類和切面類的對象創建權交給 spring
⑤在 applicationContext.xml 中配置織入關系
⑥測試代碼
?
①導入 AOP 相關坐標
<!--導入spring的context坐標,context依賴aop--> <dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.5.RELEASE</version> </dependency> <!-- aspectj的織入 --> <dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.13</version> </dependency>②創建目標接口和目標類(內部有切點)
public interface TargetInterface {public void method(); }public class Target implements TargetInterface {@Overridepublic void method() {System.out.println("Target running....");} }③創建切面類(內部有增強方法)
public class MyAspect {//前置增強方法public void before(){System.out.println("前置代碼增強.....");} }④將目標類和切面類的對象創建權交給 spring
<!--配置目標類--> <bean id="target" class="com.leon.aop.Target"></bean> <!--配置切面類--> <bean id="myAspect" class="com.leon.aop.MyAspect"></bean>⑤在 applicationContext.xml 中配置織入關系
導入aop命名空間
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">⑤在 applicationContext.xml 中配置織入關系
配置切點表達式和前置增強的織入關系
<aop:config><!--引用myAspect的Bean為切面對象--><aop:aspect ref="myAspect"><!--配置Target的method方法執行時要進行myAspect的before方法前置增強--><aop:before method="before" pointcut="execution(public void com.leon.aop.Target.method())"></aop:before></aop:aspect> </aop:config>⑥測試代碼
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class AopTest {@Autowiredprivate TargetInterface target;@Testpublic void test1(){target.method();} }?
總結
以上是生活随笔為你收集整理的xml方式实现aop-快速入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: aop简介-aop开发明确的事
- 下一篇: xml方式实现aop-切点表达式的写法