需要在没有xml配置的情况下调用方面

时间:2019-05-21 20:41:18

标签: java spring-mvc aop

我想在春季不使用xml文件运行一个方面。 我编写了以下类,AOPTest类是我的单元测试用例,它调用方法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

启用了方面

1 个答案:

答案 0 :(得分:0)

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

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