A
A
afna2016-07-08 12:44:32
Java
afna, 2016-07-08 12:44:32

How to connect Aspect using annotations?

Hello!
I master the aspects.
There is a class with a method:

public class GreetingServiceImpl implements GreetingService{

    @Override
        public String sayGreeting() {
        return "Greeting, user!";
    }
}


I want to connect aspect to this method.
I create a class:
package lessons.started;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class AspectTest {

    @Pointcut("execution(* lessons.started.GreetingServiceImpl.sayGreeting(..))")
    public void performance() {
    }

    @Before("performance()")
    public void befor() {
        System.out.println("Before running");
    }

    @AfterReturning("performance()")
    public void after() {
        System.out.println("After running");
    }
}


I get context like this:
ApplicationContext context = new AnnotationConfigApplicationContext(LessonsConfiguration.class);


LessonsConfiguration class :
@Configuration
public class LessonsConfiguration {

    @Bean
    @Qualifier("main")
    public GreetingService greetingService(){
        return new GreetingServiceImpl();
    }
}


In this case, the advice is not followed.
How will the system understand that the created aspect needs to be used?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
igor_suhorukov, 2016-07-14
@igor_suhorukov

Good afternoon!
>>How will the system know to use the created aspect?
If about aspectj itself, then it can embed the aspect (weaving) into the code during compilation or class loading. During class loading, you need to specify the aspectj java agent when starting jvm ( -javaagent: ) and add META-INF/aop.xml (or specify -Dorg.aspectj.weaver.loadtime.configuration if aop.xml is located elsewhere). Another option is to implement aspects when compiling and building a project.
But since you have Spring, the problem is solved more simply by "11.2.1 Enabling @AspectJ Support" in the XML configuration, or @EnableAspectJAutoProxy if the configuration is in the code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question