前置通知实现步骤:
a.需要导入的jar
aopaliance.jar
aspectjweaver.jar
b.配置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"
xmlns:tx="http://www.springframework.org/schema/tx "
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
c.编写
aop:每当之前add()之前 自动执行一个方法before();
add(); 业务方法(Student.java中的 add())
before(); 自动执行的通知,即aop前置通知
Student类:
package springProject;
public class Student {
public void add() {//在这个方法前执行前置通知
System.out.println(" add");
}
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="student" class="springProject.Student">
</bean>
<bean id="logBefore" class="aop.before.loginBefore">
</bean>
<aop:config>
<!-- 配置切入点 (在哪里执行通知 ) -->
<!-- =========连接线的另一方========= -->
<aop:pointcut expression="execution(public * springProject.Student.add(..))" id="poioncut"/>
<!-- advisor:相当于 链接切入点 和切面的线 -->
<!-- =========连接线========= -->
<aop:advisor advice-ref="logBefore" pointcut-ref="poioncut"/>
</aop:config>
</beans>
execution(expression)中的expression的常见范例:
test.java
package springProject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
public static void main(String[] args) {
ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student=(Student)conext.getBean("student");
//System.out.println(student);
student.add();
}
}
loginBefore.java
package aop.before;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class loginBefore implements MethodBeforeAdvice{
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("前置通知");
}
}
执行结果: