【问题标题】:Aspect weaving at compile-time doesn't work在编译时编织方面不起作用
【发布时间】:2015-02-09 16:40:07
【问题描述】:

我使用 Eclipse Kepler,Java 1.7。 我的 pom.xml 的一部分如下。 正如我在 Maven 编译期间看到的那样,根本没有关于编织的日志。我也没有任何错误。 方面也不起作用。 我究竟做错了什么? 正如我在一些例子中看到的那样,这个 pom 应该可以工作。 我在 Eclipse 中安装了 AspectJ 工具。

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.7</version>
            <configuration>
                <showWeaveInfo>true</showWeaveInfo>
                <source>${compiler.version}</source>
                <target>${compiler.version}</target>
                <Xlint>ignore</Xlint>
                <complianceLevel>${compiler.version}</complianceLevel>
                <encoding>UTF-8</encoding>
                <verbose>true</verbose>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aspects</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjrt</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjtools</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
            </plugin>

编辑: 这是我的方面代码:

package util;

import java.util.logging.Logger;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.util.StopWatch;

@Aspect
public class MyAspect {
    private static final Logger logger = Logger.getLogger(MyAspect.class.getName());

    @Around("execution(public * filter.RolesFilter.doFilter(..))")
    public Object loggingMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        Object retVal = joinPoint.proceed();

        stopWatch.stop();

        StringBuffer logMessage = new StringBuffer();
        logMessage.append(joinPoint.getTarget().getClass().getName());
        logMessage.append(".");
        logMessage.append(joinPoint.getSignature().getName());
        logMessage.append("(");
        // append args
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            logMessage.append(args[i]).append(",");
        }
        if (args.length > 0) {
            logMessage.deleteCharAt(logMessage.length() - 1);
        }
        logMessage.append(")");
        logMessage.append(" execution time: ");
        logMessage.append(stopWatch.getTotalTimeMillis());
        logMessage.append(" ms");
        System.out.println(logMessage.toString());
        logger.info(logMessage.toString());
        return retVal;
    }

}

我想用我的方面编织的方法:

package filter;

import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RolesFilter implements Filter {
    Logger logger = Logger.getLogger(RolesFilter.class.getName());

    public RolesFilter() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException {
        logger.info("This is logger message");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        String reqURI = req.getRequestURI();
        String userName = (String) session.getAttribute("username");
        Character role = (Character) session.getAttribute("role");
        try {
            if (role != null && role.charValue() == 'A') {
                if (reqURI.indexOf("/admin/") >= 0) {
                    chain.doFilter(request, response);
                } else {
                    res.sendRedirect(req.getContextPath()
                            + "/view/roles/admin/home.xhtml");
                }
            } else if (role != null && role.charValue() == 'B') {
                if (reqURI.indexOf("/biller/") >= 0) {
                    chain.doFilter(request, response);
                } else {
                    res.sendRedirect(req.getContextPath()
                            + "/biller.xhtml");
                }
            } else if (role != null && role.charValue() == 'C') {
                if (reqURI.indexOf("/customer/") >= 0) {
                    chain.doFilter(request, response);
                } else {
                    res.sendRedirect(req.getContextPath()
                            + "/customer.xhtml");
                }
            } else {
                res.sendRedirect(req.getContextPath()
                        + "/login.xhtml");
            }
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

另外,这里是maven clean compile 输出:

[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for myproject:war:0.0.1-SNAPSHOT
[WARNING] The expression ${build.sourceDirectory} is deprecated. Please use ${project.build.sourceDirectory} instead.
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject Maven Webapp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ myproject ---
[INFO] Deleting /Users/user1/git/myproject/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ myproject ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.1:compile (default-compile) @ myproject ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 41 source files to /Users/user1/git/myproject/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.007 s
[INFO] Finished at: 2015-02-16T10:00:23-08:00
[INFO] Final Memory: 12M/245M
[INFO] ------------------------------------------------------------------------

【问题讨论】:

  • 感谢您分享部分 Maven 配置,但应用程序和方面代码在哪里? Maven 控制台输出在哪里?如果没有这些信息,很难对您的问题说任何明智的事情。请更新您的问题,最好创建并分享一个最小的SSCCE 重现问题,也许在 GitHub 上。
  • 请也发布RolesFilter 类(包括包声明)以及mvn clean compile 的输出。哦,顺便说一句:如果你在 Spring 中使用原生 AspectJ,是有意还是你真的想使用 Spring AOP?在后一种情况下,方面也应该是 Spring @Component,AFAIK。
  • @kriegaex 感谢您的参与。我两个都加了。关于 AspectJ 和 Spring AOP - 我只是尝试遵循不同的教程。尽管我尝试了我发现的一切,但我未能使其工作。出了点问题,但我无法得到什么。
  • 您的 AspectJ Maven 插件未运行。您是否只是将其放入 &lt;pluginManagement&gt; 部分但忘记添加实际的 &lt;plugins&gt; 部分来激活它? Maven 输出表明了这一点,而您只从 POM 中发布了一个 sn-p,因此很难判断。
  • pluginManagement 中的任何内容都只是预配置。您还需要有一个额外的独立 plugins 部分 outside of pluginManagement 在其中声明您真正想要的预配置插件(没有版本号和配置,只有组和工件 ID)在构建期间使用。这是 Maven 基础知识。

标签: java aop aspectj aspect aspectj-maven-plugin


【解决方案1】:

您的 Maven 日志没有显示 aspectj-maven-plugin 正在执行的迹象,因此没有编织。我想您已将插件配置放入 &lt;pluginManagement&gt; 部分,但尚未从 &lt;plugins&gt; 部分引用配置的插件。这将解释缺少的插件输出。 IE。你需要这样做:

<pluginManagement>
    <plugins>
        <!-- Configure plugin here -->
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.7</version>
            <configuration>
                (...)
            </configuration>
            (...)
    </plugins>
</pluginManagement>

(...)

<plugins>
    <!-- Refer to the pre-configured plugin here in order to actually use it -->
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
    </plugin>
</plugins>

【讨论】:

    【解决方案2】:

    您是否创建了 aop.xml 并将其放在 Meta-inf 文件夹下,并且在该 aop.xml 中您是否放置了需要编织的类的包详细信息?

    【讨论】:

    • 我在方面类中使用了注解:@Around("execution(public filter.RolesFilter.doFilter(..))")
    • @Vaidy:你的回答没有意义。问题是关于编译时编织,但 aop.xml 仅用于加载时编织。
    • @Battle_Slug:@Around 建议的切入点语法错误。您没有指定方法返回类型。所以你应该看到一个 AspectJ 编译器错误。例如,这个语法是正确的:@Around("execution(public * filter.RolesFilter.doFilter(..))") - 请注意额外的*。包名称可能仍然存在问题,我不能在没有看到您的代码的情况下说。
    • @kriegaex 我添加了我方面的代码。实际上,我完全没有错误。就像我的项目中没有 AspectJ 一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多