Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP - aspect not working without xml configuration

My intention is run the aspect before get message method in service. I don't want to use xml configuration, so I add (hopefully) necessary annotation. But, when I run my application, aspect doesen't work, and nothing happen. Can You explain me why?

Service

public interface Service {
  void getMessage();
}

Service implementation

import org.springframework.stereotype.Component;

@Service
public class ServiceImpl implements Service {
  public void getMessage() {
    System.out.println("Hello world");
  }
}

Aspect

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

    @Before("execution(* com.example.aop.Service.getMessage())")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("AOP is working!!!");
    }
}

Run

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan("com.example")
public class AopApplication {

    public static void main(String[] args) {
        final ConfigurableApplicationContext run = SpringApplication.run(AopApplication.class, args);
        final Service bean = run.getBean(ServiceImpl.class);
        bean.getMessage();
    }
}

Output Only Hello world

like image 506
MatWdo Avatar asked Nov 08 '22 09:11

MatWdo


1 Answers

Probably, you have to add @Component annotation to LoggingAspect class.

like image 97
Developus Avatar answered Nov 14 '22 22:11

Developus