我想在 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/