Why my Aspect doesn't do anything?

我只是一个虾纸丫 提交于 2019-12-11 10:48:15

问题


This is a simple class which is an aspect:

package aspectTest;

import java.awt.Color;

import javax.swing.JLabel;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;


    @Aspect
    public class aspect {
        @Pointcut("execution(static String createMultiLabel(..))")
        public void multilabelCreation() {}

        @Around("multilabelCreation()")
        public String changeLabelColours(ProceedingJoinPoint thisJoinPoint) throws Throwable {

    String st = (String) thisJoinPoint.proceed();
System.out.println("fdfs");
    st = "st"+st;
    return st;
        }


}

and it's my main class:

package aspectTest;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class messagemethod {
    public static String createMultiLabel(final String msg) {

        return msg;
    }
    public static void main(String[] args) {
        String st1 = createMultiLabel("hello");
        System.out.println(st1);

    }
}

this is my the folder lib:

this is my aop.xml:

<aspectj>
    <aspects>

        <aspect name="aspectTest.aspect"/>

</aspects>

</aspectj>

and this is my Run Configuration:

my problem is that when I run my main class, it just writes hello but not hello hello, which should be because of aspect. Anyone knows why my aspect doesn't make any affect?


回答1:


This works for me.

package test;

@Aspect
public class TestAspect {
    public static String createMultiLabel(final String msg) {
        return msg;
    }
    public static void main(String[] args) {
        String st1 = createMultiLabel("hello");
        System.out.println(st1);
    }

    @Around("execution(java.lang.String test.TestAspect.createMultiLabel(java.lang.String))")
    public String aroundCreateMultiLabel(ProceedingJoinPoint joinPoint) throws Throwable {
        System.err.println("in around before " + joinPoint);
        String string = (String) joinPoint.proceed();
        System.err.println("in around after " + joinPoint);
        return string;
    }
}

Perhaps you need to redefine your project type to aspect project. Compare with your .projects file

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>Aspects</name>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.ajdt.core.ajbuilder</name>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.ajdt.ui.ajnature</nature>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>


来源:https://stackoverflow.com/questions/31783553/why-my-aspect-doesnt-do-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!