Интеграция AOP с платформой AXON

Я использую axonframework 2.3.1, для модульного тестирования приложения существует класс Aggregate, который содержит некоторые обработчики событий. Теперь я хочу, чтобы перед запуском метода commandhandler, содержащегося в классе Aggregate, я хотел применить aop tracing @Before и @After для этих методов-обработчиков.
Я использую интерфейс FixtureConfiguration и применяю newGivenWhenThenFixture к агрегатному классу, так как разводка сконфигурированных аксонов классов выполняется инфраструктурой аксонов.
Я сконфигурировал конфигурацию aop в другом файле xml и загружаю этот файл xml перед запуском тестовых случаев. Как я могу интегрировать трассировку aop с классом проводных агрегатов axon.
Спасибо

Я использовал этот пример на http://www.axonframework.org/axon-2-quickstart-guide/ В этом примере я хочу, чтобы я мог иметь возможность регистрировать сообщения до / после трассировки для class ToDoEventHandler каждый метод вызывается.

Ниже приведен аналогичный код, где я написал несколько агрегатов и аспект для настройки. У меня есть один совокупный класс

    public class ToDoItem extends AbstractAnnotatedAggregateRoot{

    @AggregateIdentifier
    private String id;

     @CommandHandler
        public ToDoItem(CreateToDoItemCommand command) {
            apply(new ToDoItemCreatedEvent(command.getToDoId(), command.getDescription()));
    }
    @CommandHandler
    public void markCompleted(MarkCompletedCommand command){
        apply(new ToDoItemCompletedEvent(id));      
    }
    public ToDoItem(){

    }

    @EventHandler
    public void on(ToDoItemCreatedEvent event){
        this.id=event.getTodoid();
    }

}

и один класс EventHandler

    public class ToDoEventHandler {

    @EventHandler
    public void handle(ToDoItemCreatedEvent event) {
        System.out.println("We are starting a task: "
                + event.getDescription() + " (" + event.getTodoid() + ")");
    }

    @EventHandler
    public void handle(ToDoItemCompletedEvent event) {
        System.out.println("We've completed a task: " + event.getTodoid());
    }

}

Файл конфигурации Spring-Axon выглядит следующим образом

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:axon="http://www.axonframework.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.axonframework.org/schema/core http://www.axonframework.org/schema/axon-core-2.0.xsd">

<axon:command-bus id="commandBus" />
<axon:event-bus id="eventBus" />

<axon:event-sourcing-repository id="toDoRepository"
    aggregate-type="com.my.axon.ToDoItem" />

<axon:aggregate-command-handler id="toDoItemHandler"
    aggregate-type="com.my.axon.ToDoItem" repository="toDoRepository"
    command-bus="commandBus" />

<axon:filesystem-event-store id="eventStore"
    base-dir="events" />


<bean
    class="org.axonframework.commandhandling.gateway.CommandGatewayFactoryBean">
    <property name="commandBus" ref="commandBus" />
</bean>

<axon:annotation-config />
<bean class="com.my.axon.ToDoEventHandler" />

<bean class="com.my.axon.AopConfigurator"></bean>

Теперь я хочу, чтобы до / после класса ToDoEventHandler каждый вызываемый метод должен иметь возможность регистрировать до и после аспектов, поэтому я создал аспект и настроил его.

/**
 * This class is used to configure the AOP related beans 
 * instead of doing the entries the beans are configured here and the
 * same effect is achieved using @EnableAspectJAutoProxy annotation. 
 * @author anand.kadhi
 *
 */
@Configuration
@EnableAspectJAutoProxy
public class AopConfigurator {

    @Bean
    public AspectRunner aspectOperation()
    {
        return new AspectRunner();
    }   
}

и аспект

    @Aspect 
    public class AspectRunner {

        /**
         * This pointcut will call respective before and after method execution 
         * points
         */
        @Pointcut("execution(* com.my.axon.ToDoEventHandler.*(..))")
        public void logging(){};

        @Before("logging()")
        public void entering(JoinPoint joinPoint)
        {

            System.out.println("After completing Class : "+joinPoint.getTarget().getClass().getName() +" and method : "+joinPoint.getSignature().getName());
        }

        @After("logging()")
        public void exiting(JoinPoint joinPoint)
        {
            System.out.println("After completing Class : "+joinPoint.getTarget().getClass().getName() +" and method : "+joinPoint.getSignature().getName());


        }
    }

и есть основной класс

public class ToDoItemRunner {

private CommandGateway commandGateway;

public ToDoItemRunner(CommandGateway commandGateway) {
    this.commandGateway = commandGateway;
}

public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-axon.xml");
    ToDoItemRunner runner = new ToDoItemRunner(applicationContext.getBean(CommandGateway.class));
    runner.run();
}

private void run() {
    final String itemId = UUID.randomUUID().toString();
    commandGateway.send(new CreateToDoItemCommand(itemId, "Need to do this"));
    commandGateway.send(new MarkCompletedCommand(itemId));
}

}

Я хочу, чтобы до / после класса ToDoEventHandler каждый вызываемый метод должен иметь возможность регистрировать до и после аспектов.

Заранее спасибо.

0 ответов

Другие вопросы по тегам