在春天用AOP登录?

Hum*_*ing 18 java spring log4j aspectj spring-mvc

我是新来的,在我的办公室里.所以我没有指导.

我需要AOP使用the 来实现日志记录log4j.

我在没有AOP基本spring MVC示例的情况下实现了日志记录?

AOP使用了aspectJ没有记录的小样本(只是制作了Sysout)?

我不知道如何整合它?

任何人都可以给我一个启动想法吗?

很好的答案肯定赞赏...

Mar*_*zee 34

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...");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需配置applicationContext.xml(或等效的):

    <aop:aspectj-autoproxy>
        <aop:include name="myLogger"/>
    </aop:aspectj-autoproxy>

    <bean id="myLogger" class="com.example.aspect.MyLogger"/>
Run Code Online (Sandbox Code Playgroud)

您将在MyLogger类中注意到我@After在方法上方指定了该类.这称为建议,它基本上指定相关方法之后调用此"log"方法.其他选择包括@Before, @Around, @AfterThrowing.

该表达式"execution(* com.example.web.HomeController.*(..))"称为切入点表达式,并指定我们所针对的内容(在本例中为HomeController类的所有方法).

PS需要将aopnamespace(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">
Run Code Online (Sandbox Code Playgroud)

  • 从[文档](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html):`您可以在Spring XML中将方面类注册为常规bean配置,或者通过类路径扫描自动检测它们 - 就像任何其他Spring管理的bean一样.但是,请注意@Aspect注释不足以在类路径中自动检测:为此,您需要添加单独的@Component注释(或者根据Spring的组件扫描程序的规则添加符合条件的自定义构造型注释). ` (2认同)