我是办公室里的新人。所以没有对我的指导。
我需要使用 log4j
来实现使用 AOP
的日志记录。
我已经在基本 spring MVC
示例中实现了没有 AOP
的日志记录?
AOP
中的小样本也使用 aspectJ
没有记录(只是制作了 Sysout
)?
不知道怎么集成?
谁能给我一个创业想法?
肯定会感谢好的答案...
最佳答案
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">
关于java - 在 Spring 使用 AOP 进行日志记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15746676/