gpt4 book ai didi

java - Spring AOP : Only Context Beans Could be Adviced?

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:46 25 4
gpt4 key购买 nike

我是 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 aspect = new LoggerAspTest(); 创建 LoggerAspTest。该方面什么都不做。

问题是:“方面是否只适用于由 Spring 的上下文实例化的 bean?”。我真的希望方面像“全局拦截器”一样工作,知道它们必须继续执行哪些方法...

提前致谢。

最佳答案

是的,它需要是 spring bean

关于java - Spring AOP : Only Context Beans Could be Adviced?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8642137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com