Spring 让我们可以很容易地使用 AOP。这是一个简单的日志记录示例:
@Aspect
public class MyLogger {
private Logger log = Logger.getLogger(getClass());
@After("execution(* com.example.web.HomeController.*(..))")
public void log(JoinPoint point) {
log.info(point.getSignature().getName() + " called...");
}
}
然后只需配置您的 applicationContext.xml(或等效项):
<aop:aspectj-autoproxy>
<aop:include name="myLogger"/>
</aop:aspectj-autoproxy>
<bean id="myLogger" class="com.example.aspect.MyLogger"/>
您会在 MyLogger 类中注意到我在方法上方指定了@After。这称为建议,它基本上指定此“日志”方法将在相关方法之后调用。其他选项包括@Before, @Around, @AfterThrowing。
表达式"execution(* com.example.web.HomeController.*(..))" 被称为切入点表达式并指定我们的目标(在本例中为 HomeController 类的所有方法)。
附: aop 命名空间 (xmlns:aop="http://www.springframework.org/schema/aop") 和模式位置(取决于版本)需要添加到您的 applicationContext.xml 顶部。这是我的设置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">