Spring Boot Web中的AOP不生效

1.问题描述

我想在一个Spring MVC Controller运行前插入一个切面,在控制台显示Hello index(index是注入切面的方法名称)。但是访问页面调用控制器的时候失败了。在切面配置类加入断点,接着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


饮歌长啸
浏览 2306回答 2
2回答

ABOUTYOU

我看了你的代码请在Demo3Application 上面添加一个 @ComponentScan(basePackages = "cn.shaytang") 注解,我已经测试了你的切面没有问题。

HUX布斯

HelloController 中的index方法的修饰符改为public即可。如下:@Controllerpublic class HelloController {    @RequestMapping(value = "")    public String index(){        return "index";    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java