AOP和execultion表達式
1、AOP相關名詞
2、AOP通知類型
1)xml方式的通知類型
a.前置通知實現步驟:
1.導入jar包
2.編寫實現類和spring上下文配置文件
HelloWorld.java
package njpji.server;
public class HelloWorld {
public void print() {
System.out.println("hello world...");
}
public void print2() {
System.out.println("welcome to beijing...");
}
}
NoticeBefore.java
package njpji.server;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class NoticeBefore implements MethodBeforeAdvice{
//編寫一個前置通知的方法
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("您好,這是前置通知");
}
}
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">
<!-- 配置前置通知:關聯方法 -->
<!-- print()方法所在類 -->
<bean id="helloWorld" class="njpji.server.HelloWorld"></bean>
<!-- before()方法所在類 -->
<bean id="noticeBefore" class="njpji.server.NoticeBefore"></bean>
<!-- 將前置通知和print()方法進行關聯 -->
<aop:config>
<!-- 配置切入點 -->
<aop:pointcut expression="execution(public void njpji.server.HelloWorld.print2()) or execution(public void njpji.server.HelloWorld.print())" id="pointCut"/>
<!-- advisor:相當於連接 "切入點" 和 "通知" 的橋樑 -->
<aop:advisor advice-ref="noticeBefore" pointcut-ref="pointCut"/>
</aop:config>
</beans>
Test.java
package njpji.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import njpji.server.HelloWorld;
public class Test {
public static void main(String[] args) {
//加載spring上下文配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
//打印輸出:hello World...
helloWorld.print();
helloWorld.print2();
}
}
2)運行截圖
總結:另外"後置通知"、“異常通知”、"環繞通知"請各位自行琢磨…