问题描述
我是办公室的新人.所以没有给我的指导.
I am new to spring in my office . So there is no guidance for me.
我需要使用 log4j
使用 AOP
实现日志记录.
I need to implement the logging with the AOP
using the log4j
.
我已经在基本的 spring MVC
示例中实现了没有 AOP
的日志记录?
I have implemented the logging without AOP
in basic spring MVC
example ?
也在AOP
中使用aspectJ
做了小样本,没有记录(只是做了Sysout
)?
Also did the small sample in AOP
using the aspectJ
without logging (just made the Sysout
) ?
我不知道如何整合它?
谁能给我一个创业的想法?
Can any one please give me a start up idea?
好的答案绝对值得赞赏......
Good answers are definitely appreciated ...
推荐答案
Spring 使我们可以很容易地使用 AOP.这是一个简单的日志记录示例:
Spring makes it really easy for us to make use of AOP. Here's a simple logging example:
@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(或等效文件):
Then simply configure your applicationContext.xml (or equivalent):
<aop:aspectj-autoproxy>
<aop:include name="myLogger"/>
</aop:aspectj-autoproxy>
<bean id="myLogger" class="com.example.aspect.MyLogger"/>
您会注意到在 MyLogger 类中,我在方法正上方指定了 @After
.这称为通知,它基本上指定将在相关方法之后调用此日志"方法.其他选项包括 @Before、@Around、@AfterThrowing
.
You'll notice in the MyLogger class that I specified @After
right above the method. This is called the advice and it basically specifies that this 'log' method will be called after the method in question. Other options include @Before, @Around, @AfterThrowing
.
表达式 "execution(* com.example.web.HomeController.*(..))"
被称为切入点表达式并指定我们的目标(在这种情况下所有方法HomeController 类).
The expression "execution(* com.example.web.HomeController.*(..))"
is called a pointcut expression and specifies what we're targeting (in this case all methods of the HomeController class).
附言aop
命名空间(xmlns:aop="http://www.springframework.org/schema/aop"
)和模式位置(取决于版本)需要是添加到您的 applicationContext.xml 的顶部.这是我的设置:
P.S. The aop
namespace (xmlns:aop="http://www.springframework.org/schema/aop"
) and the schema location (version dependent) would need to be added to your applicationContext.xml right at the top. Here is my setup:
<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">
这篇关于在春季使用 AOP 进行日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!