我是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()创建LoggerAspTest时,而是通过LoggerAspTest aspect = new LoggerAspTest();
,方面什么都不做。
问题是:“方面是否只适用于由Spring的上下文实例化的bean?”。我真的希望各个方面像“全球拦截器”一样工作,知道他们必须采取哪些方法......
提前谢谢。
答案 0 :(得分:3)
是的,它需要是春豆