I'm new to Spring AOP and I try to use an aspect for logging. Here is my configuration:
The aspect:
@Aspect
public class LoggerAspect {
@Pointcut("execution(* aop.LoggerAspTest.*(..))")
private void infoMethods(){}
@Before("infoMethods()")
public void logBefore(JoinPoint joinPoint) {
Logger logger = Logger.getLogger(joinPoint.getTarget().getClass());
logger.info("joinPoint's kind: " + joinPoint.getKind());
logger.info("joinPoint's args: " + joinPoint.getArgs());
logger.info("joinPoint's source location: " + joinPoint.getSourceLocation());
logger.info("joinPoint's staticPart: " + joinPoint.getStaticPart());
logger.info("joinPoint's targetClass: " + joinPoint.getTarget().getClass());
logger.info("joinPoint's this: " + joinPoint.getThis());
}
}
The test class:
@Component
public class LoggerAspTest {
// test method
public void getInfo() {
System.out.println("in the logger aspect test method!!!");
}
}
The class - executor:
public class Main {
// main
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");
LoggerAspTest aspect = (LoggerAspTest) ctx.getBean("aspectTest");
aspect.getInfo();
}
}
And finally - applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="aspectTest" class="aop.LoggerAspTest"/>
...
Well, everything works perfectly.
But when I change the class-executor (Main) so that I create the LoggerAspTest not by Spring's ApplicationContext.getBean(), but via LoggerAspTest aspect = new LoggerAspTest();
the aspect does nothing.
The question is: "Is it true that aspects work only with beans that were instantiated by Spring's context?". I really expected aspects to work like "global interceptors", that know which methods they must proceed on...
Thank's in advance.
Yes it needs to be spring bean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With