Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP: Only Context Beans Could be Adviced?

Tags:

java

spring

aop

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.

like image 983
Dmitry Avatar asked Dec 27 '11 07:12

Dmitry


1 Answers

Yes it needs to be spring bean

like image 100
jmj Avatar answered Oct 25 '22 13:10

jmj