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)运行截图
总结:另外"后置通知"、“异常通知”、"环绕通知"请各位自行琢磨…