具有 Gradle 切入点或建议的 AspectJ 不起作用 - 不使用 spring 或 android

AspectJ with Gradle Pointcut or Advice not working - NOT using spring or android

您好,我正在构建一个用于 AWS 组件之间消息传递的库,因此我需要一个轻量级的解决方案。解决方案的一部分要求我监听何时调用带注释的方法,因此我想我会使用切入点并实现关于在达到该切入点时该做什么的建议。

gradle.build 脚本如下所示:

buildscript {
    ext {
        // some company-specific config here
        nexus = {
            credentials {
                username nexusBuildUserToken
                password nexusBuildPassToken
            }
            url nexusRepoURL
        }
    }

    repositories {
        mavenCentral()
        maven(nexus)
    }


    dependencies {
        classpath("net.researchgate:gradle-release:$gradleReleasePluginVersion")
        classpath("gradle.plugin.aspectj:gradle-aspectj:$gradleAspectJPluginVersion")

    }
}

apply plugin: 'java'

// IDE
apply plugin: 'idea'
apply plugin: 'eclipse-wtp'

apply plugin: "aspectj.gradle"

jar {
    enabled = true
}

// project artifact info
group = groupId
archivesBaseName = artifactId

repositories {
    mavenCentral()
    maven(nexus)
    maven {
        url "https://dl.bintray.com/findify/maven"
    }

}

dependencies {

    compile("org.aspectj:aspectjtools:$aspectjVersion")

    compile("org.apache.commons:commons-lang3:${commonsLang3Version}")
    compile("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${jacksonDataformatYamlVersion}")

    compile("org.elasticmq:elasticmq-rest-sqs_2.11:0.14.1")
    compile("com.amazonaws:aws-java-sdk-sqs:${awsMessagingVersion}")
    compile("com.amazonaws:aws-java-sdk-sns:${awsMessagingVersion}")
    compile("au.com.auspost:json-encryption:${jsonEncryptionVersion}")

    compile("org.apache.commons:commons-lang3:${commonsLang3Version}")
    compile("org.reflections:reflections:${reflectionsVersion}")
    compile("redis.clients:jedis:${jedisVersion}")
    compile("org.aspectj:aspectjweaver:$aspectjVersion")
    compile("org.aspectj:aspectjrt:$aspectjVersion")

    testCompile("junit:junit:${jUnitVersion}")
    testCompile("org.mockito:mockito-core:${mockitoCoreVersion}")
    testCompile("org.assertj:assertj-core:${assertjVersion}")
    testCompile("ai.grakn:redis-mock:${embeddedRedisVersion}")
    testCompile("org.slf4j:slf4j-simple:1.7.25")
    testCompile("ch.qos.logback:logback-core:1.2.3")
    testCompile(group: 'io.findify', name: 'sqsmock_2.11', version: '0.3.2')
}

如您所见,我包含了所有 aspectj 库,以确保我没有遗漏任何我需要的东西(请随时告诉我我不需要的东西)。

我希望编织的class是这样的:

@Aspect
public class TopicSenderManager {

    private ThreadPoolFactory threadPoolFactory;

    private CorrelationService correlationService = new CorrelationService.Default();

    private Map<String, TopicSenderProcessor> topicSenderProcessors = new HashMap<>();


    private ExecutorService executor;

    public TopicSenderManager(Map<String, TopicSenderProcessor> topicSenderProcessors) {
        this.threadPoolFactory = new ThreadPoolFactory.Default();
        this.topicSenderProcessors = topicSenderProcessors;
        executor = threadPoolFactory.create(topicSenderProcessors.size(), "TopicSender");
    }

    @Around("@annotation(topicSender) && execution(* *(..))")
    public Object sendMessageToTopic(ProceedingJoinPoint pjp, TopicSender topicSender) throws Throwable {

        TopicSenderProcessor topicSenderProcessor = getProcessor(topicSender.topicAlias(), topicSender.eventType());
        topicSenderProcessor.setCorrelationId(correlationService.read());
        Object[] args = pjp.getArgs();
        if (args == null || args.length != 1) {
            throw new Exception("naughty, naughty");
        } else {
            topicSenderProcessor.setEventMessage((EventMessage) args[0]);
            executor.execute(topicSenderProcessor);
        }    
        return pjp.proceed();
    }

    public Map<String, TopicSenderProcessor> getTopicSenderProcessors() {
        return topicSenderProcessors;
    }

    public TopicSenderProcessor getProcessor(String topic, String eventType) {
        String senderKey = topic + "," + eventType;
        return topicSenderProcessors.get(senderKey);
    }
}

我希望这会做的是获取用 @TopicSender 注释的方法的每次执行(调用),并在线程池的线程中执行关联的处理器。

我查看了 TopicSenderManager 的反编译 class,如下所示:

@Aspect
public class TopicSenderManager {
    private ThreadPoolFactory threadPoolFactory = new Default();
    private CorrelationService correlationService = new au.com.auspost.messaging.CorrelationService.Default();
    private Map<String, TopicSenderProcessor> topicSenderProcessors = new HashMap();
    private ExecutorService executor;

    public TopicSenderManager(Map<String, TopicSenderProcessor> topicSenderProcessors) {
        this.topicSenderProcessors = topicSenderProcessors;
        this.executor = this.threadPoolFactory.create(topicSenderProcessors.size(), "TopicSender");
    }

    @Around("@annotation(topicSender) && execution(* *(..))")
    public Object sendMessageToTopic(ProceedingJoinPoint pjp, TopicSender topicSender) throws Throwable {
        TopicSenderProcessor topicSenderProcessor = this.getProcessor(topicSender.topicAlias(), topicSender.eventType());
        topicSenderProcessor.setCorrelationId(ajc$inlineAccessFieldGet$au_com_auspost_messaging_send_topic_TopicSenderManager$au_com_auspost_messaging_send_topic_TopicSenderManager$correlationService(this).read());
        Object[] args = pjp.getArgs();
        if (args != null && args.length == 1) {
            topicSenderProcessor.setEventMessage((EventMessage)args[0]);
            ajc$inlineAccessFieldGet$au_com_auspost_messaging_send_topic_TopicSenderManager$au_com_auspost_messaging_send_topic_TopicSenderManager$executor(this).execute(topicSenderProcessor);
            return pjp.proceed();
        } else {
            throw new Exception("naughty, naughty");
        }
    }

    public Map<String, TopicSenderProcessor> getTopicSenderProcessors() {
        return this.topicSenderProcessors;
    }

    public TopicSenderProcessor getProcessor(String topic, String eventType) {
        String senderKey = topic + "," + eventType;
        return (TopicSenderProcessor)this.topicSenderProcessors.get(senderKey);
    }

    public static TopicSenderManager aspectOf() {
        if (ajc$perSingletonInstance == null) {
            throw new NoAspectBoundException("au.com.auspost.messaging.send.topic.TopicSenderManager", ajc$initFailureCause);
        } else {
            return ajc$perSingletonInstance;
        }
    }

    public static boolean hasAspect() {
        return ajc$perSingletonInstance != null;
    }

    static {
        try {
            ajc$postClinit();
        } catch (Throwable var1) {
            ajc$initFailureCause = var1;
        }

    }
}

我认为这就是应该发生的编织。

下一步是设置一个(某种)单元测试来演示我想要的行为:

首先,我定义了一个简单的示例,说明了我要拦截的那种方法:

public class SenderT1E1 {

    @TopicSender(topicAlias = "t1", eventType = "a.c.a.e1")
    public void aSendingMethod(EventMessage<TestMessage> eventMessage) {
        // do what you like before sending the message
    }
}

然后看它的测试:

public class SenderE1T1Test {

    static TopicSenderManager manager;

    @BeforeClass
    public static void setUp() throws Exception {

        MockAmazonClient snsClient = new MockAmazonClient();

        TopicSenderFactory senderFactory = new TopicSenderFactory();

        PublishResult publishResult = new PublishResult().withMessageId("E1T1");

        manager = senderFactory.make(snsClient.amazonSNS(publishResult), "aws-send-test.properties");
    }

    @Test
    public void whenSenderIsCalledMessageIsSent() {
        SenderT1E1 target = new SenderT1E1();

        EventMessage message = new EventMessage<>();
        message.setEventType("a.c.a.e1");
        message.setPayload(new TestMessage());

        target.aSendingMethod(message);

        TopicSenderProcessor processor = manager.getProcessor("http://localhost:8001/topic/t1", "a.c.a.e1");

        assertThat(manager.getTopicSenderProcessors().entrySet().size(), is(2));
        manager.getTopicSenderProcessors().forEach((k,v) -> System.out.println(k + ",  " + v));

        assertThat(processor, is(notNullValue()));

        // now, did it execute...
        assertThat(processor.getEventMessage(), is(notNullValue()));
        assertThat(processor.getLastPublishRequest(), is(notNullValue()));
        assertThat(processor.getLastPublishResult(), is(notNullValue()));
    }
}

基本上,// now did it execute... 行之前的所有内容都有效,但在那之后的所有内容都是空的。所以看起来切入点从未达到。

那么,织布是不是工作不正常? @Around 规范中的切入点和建议不正确吗?是否有某种运行时触发器,我忘记了?还是其他原因?

I thought I should make a statement here: the reason I'm not using spring is that I have found that the number of dependencies leads to a really bloated library and I'm trying to keep it as trim as possible. I want the speed benefits of aspectJ and i would prefer compile time weaving because this is a library to be used in applications I will resort to spring if I have to, but it really is a last resort.

问题出在其他类别中。切入点未被触发的原因是因为我正在使用编译时织入,而织入目标 class 在运行时不在 class 路径中。 编织目标 class 在 src/test/java 中,而切入点在 src/main/java 中,当编译应用程序时,src/test/java 不在视线范围内。我需要的是运行时编织,以便可以发现和编织测试 class,然后切入点就可以工作了。 不幸的是,运行时编织是一项昂贵的操作,因此不适合我的目的,因此我转而使用侦听器模式。从实施者的角度来看,它并不那么干净,但在性能方面要好得多