Spring AspectJ不执行 之前的建议

问题描述 投票:0回答:1

我很抱歉可能会重复这个问题(因为我在许多其他SO网站上看到过),然而,我不知道在这一点上还能尝试什么。

我正试图建立一个简单的AspectJ Spring应用程序。一旦我有了一个工作实例,我想可能创建一个通用的库,可以通过注释在我的团队中使用,所以我对使用AspectJ非常感兴趣,因为我认为它可以简化很多我试图做的事情。

以下是我的代码。

AspectDemoApplication.class -- 我的主要应用开始点。我正在初始化一个新的Account对象并调用方法,希望运行时能看到这个方法的建议。

public class AspectDemoApplication {
    public static void main(String[] args) {
        Account acct = new Account();
        acct.sayHello();
    }
}

Account.class--持有该方法的服务类。

public class Account {
    public String sayHello() {
        System.out.println("hello from method");
        return "hello";
    }
}

LogAspect.class--我的方面类,我在这里定义了点选和建议。

@Aspect
//@Component
public class LogAspect {
    @Pointcut(value = "execution(* com.rob.aspectdemo.Account.sayHello(..))")
    private void logBefore() { }

    @Before("logBefore()")
    public String print() {
        System.out.println("before hello");
        return null;
    }
}

AspectJConfig.class - 我的AspectJ配置类。大多数在线资源使用.xml配置,但从EnableAspectJAutoProxy的Javadocs上看,它说它的功能是一样的。

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = "com.rob")
public class AspectJConfig {
    @Bean
    public LogAspect getLogAspect() {
        return new LogAspect();
    }
    @Bean
    public Account getAccount() {
        return new Account();
    }
}

build.gradle - 我的gradle文件显示了我的依赖关系(我可以看到我在外部libs中有 aspectjrt.jar)。

implementation 'org.springframework:spring-core:5.2.7.RELEASE'
implementation 'org.springframework:spring-context:5.2.7.RELEASE'
implementation 'org.springframework:spring-aop:5.2.7.RELEASE'
implementation 'org.aspectj:aspectjrt:1.9.5'
implementation 'org.aspectj:aspectjweaver:1.9.5'
implementation 'org.aspectj:aspectjtools:1.9.5'

我的问题是,当我启动应用程序时(调用main()方法),它能够打印Account.sayHello()方法中的println语句,但不能打印建议中的println。

我试过使用这些在线指南(以及许多其他SO的链接),但没有用(大多数网站都是这样说明的)。

mkyong

春季AOP

我正在使用IntlliJ v2020.1,即使在这个IDE中,我的Before建议旁边也有一个符号,上面写着 "This advice advises no methods"。但是当我使用IDE的PointcutExpression Fragment工具时,它说Pointcut语法是正确的。

任何帮助都将是非常感激的! 谢谢您!我为可能重复这个问题而道歉。

spring aop aspectj spring-aop
1个回答
1
投票

以下代码将创建一个Spring应用上下文,并从上下文中获取账户Bean。

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AspectDemoApplication {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AspectJConfig.class);
        ctx.registerShutdownHook();
        Account acct = ctx.getBean(Account.class);
        acct.sayHello();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.