I made a tiny app to check a few things. Here's the code (assume all the files are in the same package)
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class Config {
}
@Component
public class SomeBean {
public SomeBean() {
System.out.println("Creating SomeBean...");
}
public String someAspectedMethod() {
return "some string";
}
}
@Aspect
@Component // note this
public class SomeAspect {
public SomeAspect() {
System.out.println("Creating SomeAspect...");
}
@Around("execution(String SomeBean.someAspectedMethod())")
public Object methodAdvice(ProceedingJoinPoint joinPoint) {
System.out.println("Running methodAdvice()..."); // never gets printed
Object object;
try {
object = joinPoint.proceed();
} catch (Throwable e) {
throw new RuntimeException(e);
}
return object;
}
}
public class App {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(Config.class);
SomeBean someBean = context.getBean(SomeBean.class);
String returnedVal = someBean.someAspectedMethod();
System.out.println(returnedVal);
System.out.println(returnedVal.getClass());
}
}
Console output:
Creating SomeAspect...
Creating SomeBean...
Running methodAspect()...
some string
class java.lang.String
I noticed that once I remove the @Component
annotation, the aspect is no longer applied
@Aspect
// @Component
public class SomeAspect {
Console output:
Creating SomeBean...
some string
class java.lang.String
Which begs the question: why isn't @Aspect
a @Component
(stereotype annotation) just like @Service
, @Repository
and a few others? And if @Component
is not necessary for aspect classes, then why does the lack of it effectively disables my aspect?
This doesn't answer my question
@Aspect
is part of the AspectJ library, which is a stand-alone library that shipped with Spring and therefore, Spring can't change the @Aspect
annotation source code to add the meta @Component
(spring can't make @Aspect
a stereotype in another word)
@Aspect
is part of aspectj annotations: org.aspectj.lang.annotation.Aspect
for
if @Component is not necessary for aspect classes
@Component
is there just to register the Aspect in the application context via component scan (@ComponentScan
that you add to Config
class let Spring search for stereotype annotations and register them in the application context)