log4j 在 Spring 用AOP进行日志记录?

k4ymrczo  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(187)

我对办公室的Spring还不熟悉,所以没有什么指导。
我需要使用log4j来实现AOP的日志记录。
我已经在基本的spring MVC示例中实现了没有AOP的日志记录。
同样在AOP中做了小样本使用aspectJ而没有日志记录(只是做了Sysout)?
我不知道怎么整合它?
有谁能给予我一个开始的想法吗?
好的答案绝对是赞赏...

7xzttuei

7xzttuei1#

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。这被称为advice,它基本上指定了这个'log'方法将在所讨论的方法之后被调用。其他选项包括@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">
to94eoyn

to94eoyn2#

您需要执行几个步骤来集成Aspectj:

  1. Install AspectJ
    1.将aop.xml添加到项目中的META-INF\aop.xml
    1.在项目类路径中添加aspectjrt-x.x.0.jar和aspectjweaver-x.x.0.jar
    1.将-javaagent:/aspectj安装路径/aspectjweaver-1.7.0.jar添加到服务器的JVM中。
    下面是一个示例aop.xml:
<aspectj>
 <aspects>
  <aspect name="test.MySimpleLoggerAspect" />
 </aspects>
 <weaver>
  <include within="test.myproject.*" />
 </weaver>     
</aspectj>

如果您已经在使用Spring,那么最好使用Spring来简化您的设置。

相关问题