我是Spring AOP和注释的新手。我试着编写一个使用Aspect的简单程序。我无法弄清楚我哪里出错了。它没有打印出我所看到的内容。
package com.business.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@EnableAspectJAutoProxy
@Configuration
public class PrintMain {
public static void main(String[] args) {
// Do I always need to have this. Can't I just use @Autowired to get beans
ApplicationContext ctx = new AnnotationConfigApplicationContext(PrintMain.class);
CheckService ck = (CheckService)ctx.getBean("service");
ck.print();
}
@Bean(name="service")
public CheckService service(){
return new CheckService();
}
}
package com.business.main;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SimpleAspect {
@Around("execution(* com.business.main.CheckService.*(..))")
public void applyAdvice(){
System.out.println("Aspect executed");
}
}
package com.business.main;
import org.springframework.stereotype.Component;
@Component
public class CheckService{
public void print(){
System.out.println("Executed service method");
}
}
输出:已执行的服务方法
我希望打印我在Aspect中的内容
答案 0 :(得分:1)
我认为你的@Component不起作用!
也许,你需要@ComponentScan
@EnableAspectJAutoProxy
@ComponentScan
@Configuration
public class PrintMain {
public static void main(String[] args) {
// Do I always need to have this. Can't I just use @Autowired to get beans
ApplicationContext ctx = new AnnotationConfigApplicationContext(TNGPrintMain.class);
CheckService ck = (CheckService)ctx.getBean("service");
ck.print();
}
@Bean(name="service")
public CheckService service(){
return new CheckService();
}
}