春季AOP:只能建议使用Context Bean? [英] Spring AOP: Only Context Beans Could be Adviced?
问题描述
我是Spring AOP的新手,我尝试使用一个方面进行日志记录.这是我的配置:
I'm new to Spring AOP and I try to use an aspect for logging. Here is my configuration:
方面:
@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:
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"/>
...
嗯,一切正常.
但是,当我更改类执行器(主要)时,不是通过Spring的ApplicationContext.getBean()创建LoggerAspTest,而是通过LoggerAspTest aspect = new 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.
问题是:方面仅适用于由Spring上下文实例化的bean是真的吗?".我真的希望像全局拦截器"这样的方面能够工作,它们知道它们必须在哪些方法上进行...
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...
先谢谢您.
推荐答案
是的,它必须是Spring bean
Yes it needs to be spring bean
这篇关于春季AOP:只能建议使用Context Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!