gpt4 book ai didi

java - Spring AOP - 无法执行方面

转载 作者:行者123 更新时间:2023-12-01 09:11:42 25 4
gpt4 key购买 nike

我是 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");
}
}

输出:执行的服务方法

我希望打印我的方面中的内容

最佳答案

我认为你的@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();
}

}

关于java - Spring AOP - 无法执行方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878021/

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