MatWdo
MatWdo

Reputation: 1740

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

Upvotes: 5

Views: 2054

Answers (2)

Developus
Developus

Reputation: 1462

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

Upvotes: 1

Strelok
Strelok

Reputation: 51441

I believe the pointcut expression syntax should be like this:

@Before("execution(void com.aop.service.Service+.getMessage(..))")

The + is used to apply the pointcut to subtypes (you can replace void with * too.

Upvotes: 0

Related Questions