java - Spring Boot Web中的AOP不生效

 youxiang574传奇_257 发布于 2022-10-31 00:08

1.问题描述
我想在一个Spring MVC Controller运行前插入一个切面,在控制台显示Hello indexindex是注入切面的方法名称)。但是访问页面调用控制器的时候失败了。在切面配置类加入断点,接着DEBUG,显示访问页面的时候,切面配置类甚至都没有运行,三段代码如下,您能帮我看一看问题所在吗?
2.代码如下:
(1)入口类:

@SpringBootApplication
@EnableAspectJAutoProxy
public class Demo3Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo3Application.class, args);
        System.out.println("start!");
    }
}

(2)切面配置类

@Aspect
@Component
public class HelloAspect {
    @Before(value = "execution(String cn.shaytang.HelloController.index())")
    public void before(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        System.out.println("Hello" + method.getName());
    }
}

(3)加入切面的控制器

@Controller
public class HelloController {
    @RequestMapping(value = "")
    String index(){
        return "index";
    }
}

3.控制台结果

start!
2016-04-26 00:08:07.500  INFO 4302 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-04-26 00:08:07.500  INFO 4302 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-26 00:08:07.516  INFO 4302 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms
2 个回答
  • HelloController 中的index方法的修饰符改为public即可。如下:

    @Controller
    public class HelloController {
        @RequestMapping(value = "")
        public String index(){
            return "index";
        }
    }
    2022-10-31 22:31 回答
  • 谢谢邀请:
    我看了你的代码请在Demo3Application 上面添加一个 @ComponentScan(basePackages = "cn.shaytang") 注解,我已经测试了你的切面没有问题。

    2022-10-31 22:31 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有