基於註解形式的AOP實現
1、之前我們在AOP和execution表達式一文中講過如果通過接口實現AOP,現在我們通過註解來實現AOP.
2、實現:
1)導入jar包:
同AOP和execution表達式一樣
2)我們來理清楚他的實現邏輯過程
第一步:編寫好業務類和通知方法
第二步:在使用註解聲明通知方法爲前置通知、後置通知、或者環繞通知
第三步:使用註解聲明插入點:
@Before(value = "execution(public void njpji.server.Study.study())")
第四步:在spring上下文文件中開啓對aop的支持
<!-- 開啓註解對AOP的支持 -->
<aop:aspectj-autoproxy />
第五步:編寫測試類進行測試
3)代碼:
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 業務類所在位置 -->
<bean id="Study" class="njpji.server.Study" />
<!-- 通知方法所在位置 -->
<bean id="NoticeBefore" class="njpji.server.NoticeBefore"/>
<!-- 開啓註解對AOP的支持 -->
<aop:aspectj-autoproxy />
</beans>
Study.java
package njpji.server;
public class Study {
public void study() {
System.out.println("學習java");
}
}
NoticeBefore.java
package njpji.server;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //聲明他是一個通知
public class NoticeBefore {
//前置通知註解
@Before(value = "execution(public void njpji.server.Study.study())")
public void before() {
System.out.println("前置通知....");
}
}
Test.java
package njpji.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import njpji.server.Study;
public class Test {
public static void main(String[] args) {
//加載spring上下文配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Study study = (Study) context.getBean("Study");
//打印輸出
study.study();
}
}
3)截圖: