开发者社区 问答 正文

Spring Boot Web中的AOP不生效

我想在一个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.控制台结果

tart!
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

展开
收起
蛮大人123 2016-03-12 15:13:57 8445 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    HelloController 中的index方法的修饰符改为public即可。如下:

    @Controller
    public class HelloController {
        @RequestMapping(value = "")
        public String index(){
            return "index";
        }
    }
    2019-07-17 19:01:01
    赞同 展开评论