How to understand Spring @ComponentScan

前端 未结 1 1172
渐次进展
渐次进展 2020-12-09 03:42

I\'m following a tutorial about Spring MVC and I cannot understand something about the @ComponentScan annotation even after reading the spring API doc, so here

相关标签:
1条回答
  • 2020-12-09 04:20

    Simply put - @ComponentScan tells Spring in which packages you have annotated classes which should be managed by Spring. So, for example, if you have a class annotated with @Controller which is in a package which is not scanned by Spring, you will not be able to use it as Spring controller.

    Classes annotated with @Configuration is a new way of configuring Spring using annotations instead of XML files (it's called Java configuration). Spring needs to know which packages contain spring beans, otherwise you would have to register each bean individually. That's what @ComponentScan is used for.

    In your example, you tell Spring that package com.apress.prospringmvc.bookstore.web contains classes which should be handled by Spring. Spring then finds a class annotated with @Controller, and processes it, which results in all requests coming to /index.htm being intercepted by the controller.

    When the request is intercepted, Spring needs to know what response to send to the caller. Since you return an instance of ModelAndView, it will try to find a view (JSP page) called index in your project (details of this depend on configured view resolvers), and renders it to the user.

    If @Controller annotation wasn't present, or that package wasn't scanned by Spring, all of this would not be possible.

    0 讨论(0)
提交回复
热议问题