【发布时间】:2026-02-27 07:40:01
【问题描述】:
让我首先指出,我面临的问题是
interceptThoughts(String thoughts)
方法,从第一个代码块开始,而不是打印
我正在运行 Spring in Action 的教程。有一个Magician 类与implements MindReader 接口与方法interceptThoughts(String thoughts) 和getThoughts()
@Aspect
public class Magician implements MindReader {
private String thoughts;
@Pointcut("execution(* com.underdogdevs.myspringaspectj."
+ "Thinker.thinkOfSomething(String)) && args(thoughts)")
public void thinking(String thoughts) {
}
@Override
@Before("thinking(thoughts)")
public void interceptThoughts(String thoughts) {
System.out.println("Intercepting volunteer's thoughts : " + thoughts);
this.thoughts = thoughts;
}
@Override
public String getThoughts() {
return thoughts;
}
}
切面应该读取Volunteer的思想implements Thinker接口,使用方法thinkOfSomething(String thoughts)
public class Volunteer implements Thinker {
private String thoughts;
@Override
public void thinkOfSomething(String thoughts) {
this.thoughts = thoughts;
System.out.println("Something");
}
public String getThoughts() {
return thoughts;
}
}
我的 java BeanConfig 带有 Magician 和 Volunteer
@Configuration
public class BeanConfig {
@Bean
public MindReader magician() {
return new Magician();
}
@Bean
public Thinker volunteer() {
return new Volunteer();
}
}
我正在尝试运行它以获取Magician 方法以打印interceptThoughts 方法中的行
public class App {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-idol.xml");
System.out.println();
Thinker volunteer = (Thinker)context.getBean("volunteer");
volunteer.thinkOfSomething("This is what I'm thinking");
}
}
- 没有错误
- 没有例外
- 包在
@Pointcut(execution(Magician方面是正确的 -
我的 Spring 配置 xml 中有这两项
<context:component-scan base-package="com.underdogdevs.myspringaspectj" /> <aop:aspectj-autoproxy />
问题是来自
Magician方面的@Before没有按应有的方式打印。 我在这里遗漏了什么吗?为什么不打印?我还有其他方面的方法,它们不带参数并且运行得很好。我没有正确传递参数值吗?
【问题讨论】:
-
这可能是一个疯狂的猜测,因为你的方面对我来说似乎是正确的;您是否尝试将 Volunteer 和 Magician 注释为
@Components ?还是将切入点放在@Before 注释内? -
!guido 我刚试过,但它不起作用。我想这就是 this
<context:component-scan.../>的用途,在上下文中扫描 bean,而没有具体指定@Component -
好吧,实际上
context:component-scan是用于扫描类以搜索 @Component 注释(以及@Service、@Controller,...以及@Configuration,它是元-注解@Component)