1.定义切面类
如下函数,将beforeMethod应用到其他函数中。
package test;
import org.aspectj.lang.JoinPoint;
public class LoggingAspect {
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println(methodName + " begins.");
}
}
2.定义配置文件
如下所示,分别定义person和loggingAspect的bean,然后定义一个aop:config把他们两个关联起来即可。
这里仅定义了前置通知作为实例,其他的通知都是类似的。另外,Person类过于简单,实现省略掉了。
<?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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="test.Person"></bean>
<!-- 配置切面的bean -->
<bean id="loggingAspect" class="test.LoggingAspect"></bean>
<!-- 建立切面关联 -->
<aop:config>
<aop:pointcut expression="execution(public void test.Person.setName(String))" id="setNamePointcut"/>
<aop:aspect ref="loggingAspect" order="1">
<aop:before method="beforeMethod" pointcut-ref="setNamePointcut"/>
</aop:aspect>
</aop:config>
</beans>
3.测试类
这里setName调用时,就会执行切面函数。
public class MainTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("aopconfig.xml");
Person person = ctx.getBean("person", Person.class);
person.setName("high");
}
}
<完>