【问题标题】:Need to call aspect without xml configuration需要在没有xml配置的情况下调用aspect
【发布时间】:2019-05-22 09:00:14
【问题描述】:

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

启用了方面

【问题讨论】:

    标签: java spring-mvc aop


    【解决方案1】:

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

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

    【讨论】:

    • 感谢更新,什么是 SpringRunner.class @Nikolay Shevchenko
    • @user3684675 Spring 对 JUnit 的 Runner 的实现
    • ok..我将尝试从 main() 方法调用并在不使用 @RunWith..的情况下进行测试。
    • Shevchenko - 我已经添加了你上面提到的..但它仍然没有在 MyAspect 类中调用 Before
    猜你喜欢
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2014-11-18
    • 2017-03-19
    • 2014-12-05
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多