我是 Spring AOP 的新手,我尝试使用方面进行日志记录。这是我的配置:
方面:
@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());
}
}
测试类:
@Component
public class LoggerAspTest {
// test method
public void getInfo() {
System.out.println("in the logger aspect test method!!!");
}
}
类-执行者:
public class Main {
// main
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");
LoggerAspTest aspect = (LoggerAspTest) ctx.getBean("aspectTest");
aspect.getInfo();
}
}
最后 - 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"/>
...
嗯,一切都很完美。
但是当我更改类执行器(Main)以便我不是通过 Spring 的 ApplicationContext.getBean() 而是通过创建 LoggerAspTestLoggerAspTest aspect = new LoggerAspTest();
该方面不执行任何操作。
问题是:“方面真的只适用于由 Spring 上下文实例化的 bean 吗?”。我真的希望各个方面能够像“全局拦截器”一样工作,知道它们必须继续执行哪些方法......
提前致谢。