将AspectJ添加到现有项目中

时间:2013-05-30 12:57:12

标签: spring oauth-2.0 spring-aop

我正在使用spring-security项目来尝试OAuth2服务器实现。我从https://github.com/SpringSource/spring-security-oauth克隆了git项目。

示例正如文档所述。现在跟踪流程,我想使用AOP向现有代码添加函数入口/出口。为此,我做了以下更改:

  • 添加了一个“Watcher.java”类(下面的代码)
  • 在pom.xml中添加了AspectJ依赖项

    <dependency>
        <groupId>aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.5.3</version>
    </dependency>
    
  • 项目构建并运行

  • 但是没有看到每个函数的AspectJ标记

是否可以使用此方法添加函数入口/出口日志记录而无需更改原始代码?

Watcher.java:

package org.springframework.security.oauth.examples.sparklr;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@Aspect
public class Watcher {

    @Pointcut("execution(* *(..))")
    public void watch() {
    }

    @Before("watch()")
    public void preWatch(JoinPoint joinPoint) {

        if (joinPoint.getArgs().length > 0) {
            String[] args = new String[joinPoint.getArgs().length];

            System.arraycopy(joinPoint.getArgs(), 0, args, 0,
            joinPoint.getArgs().length);

            System.out.println("-> " + joinPoint.toShortString()
                    + Arrays.toString(joinPoint.getArgs()));
        } else {
            System.out.println("-> " + joinPoint.toShortString());
        }

        System.out.println("Args: " + joinPoint.getArgs().length);
    }

    @AfterReturning("watch()")
    public void postWatch(JoinPoint joinPoint) {
        System.out.println("<- " + joinPoint.toShortString());
    }
}

1 个答案:

答案 0 :(得分:0)

您应该在弹簧配置中启用AspectJ(以自动扫描您的注释)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="..."/>
    <aop:aspectj-autoproxy />
    ...
</beans>

也许你也会对你的项目spring-aop依赖。

相关问题