2013-05-30 167 views
0

我正在使用spring-security項目來嘗試OAuth2服務器實現。我從https://github.com/SpringSource/spring-security-oauth克隆了git項目。將AspectJ添加到現有項目

該示例按記錄的方式工作。現在要跟蹤流程,我想使用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()); 
    } 
} 

回答

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> 

也許你會NEDD到spring-aop依賴於你的項目了。