java - 需要调用aspect而无需xml配置

标签 java spring-mvc aop

我想在 spring 中运行一个方面而不使用 xml 文件。 我编写了如下类,AOPTest 类是我的 junit 测试用例,它调用方法 showProducts(),但在调用 showProducts() 之前 我需要调用方面 logBeforeV1(..) ,它在下面的代码中没有被调用。如有任何意见,我们将不胜感激。

package com.aop.bl;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackages="com.aop.bl")
@EnableAspectJAutoProxy
public class MyBusinessLogicImpl {
    public void showProducts() {
        //business logic
        System.out.println("---show products called from business layer----");
    }
}
package com.aop.bl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
    @Before("execution(* com.aop.bl.MyBusinessLogicImpl.showProducts(..))") // point-cut expression
    public void logBeforeV1(JoinPoint joinPoint) {
        System.out.println("------------calling showProducts() from MyAspect---------------: ");
    }
}
package com.aop.test;
import org.junit.Test;
import com.aop.bl.*;

public class AOPTest {
    @Test
    public void test() {
        MyBusinessLogicImpl myObj = new MyBusinessLogicImpl();
        myObj.showProducts(); 
    }
}

我的输出如下:

---show products called from business layer----

预期输出:

------------calling showProducts() from MyAspect---------------:
---show products called from business layer----

注意:我已使用 @EnableAspectJAutoProxy

启用了方面

最佳答案

您的单元测试是在 Spring 上下文之外启动的,因此您需要导入配置

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { MyBusinessLogicImpl.class })
public class AOPTest {
    ...
}

关于java - 需要调用aspect而无需xml配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56246053/

相关文章:

java - 从 Java 代码调用 shell 命令时无法获取输出

java - 在运行时更改 CommonsMultipartResolver 的 maxUploadSize

aop - 如何在 spring aop 中将上下文参数传递给建议

Ninject 公约和拦截

java - 在简单的 Scala 应用程序中嵌入终端窗口

java - 与其他语言相比,使用 Java 开发服务器端应用程序有哪些优势?

Java 封装和 OOP 最佳实践

java - 信息 : No Spring WebApplicationInitializer types detected on classpath

java - Spring加载Tomcat资源

java - 为 Spring MVC Controller - AOP 或 Spring Security 的方法传递密码?