如何了解Spring @ComponentScan


问题内容

我正在关注有关Spring MVC的教程,即使阅读了Spring API文档,我也无法理解有关@ComponentScan批注的信息,因此,这里是示例代码

配置视图控制器

package com.apress.prospringmvc.bookstore.web.config;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
// Other imports ommitted
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.apress.prospringmvc.bookstore.web" })
public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter {
    // Other methods ommitted
    @Override
    public void addViewControllers(final ViewControllerRegistry registry) {
        registry.addViewController("/index.htm").setViewName("index");
    }
}

基于注释的控制器

package com.apress.prospringmvc.bookstore.web;    
import org.springframework.stereotype.Controller;    
import org.springframework.web.bind.annotation.RequestMapping;    
import org.springframework.web.servlet.ModelAndView;    
@Controller    
public class IndexController {    
@RequestMapping(value = "/index.htm")    
    public ModelAndView indexPage() {     
        return new ModelAndView(“index");    
    }    
}

我的问题是:

对于View Controller,通过添加
@Configuration和
@ComponentScan(basePackages = {“
com.apress.prospringmvc.bookstore.web”}),在后台会做什么?包com.apress.prospringmvc.bookstore.web是否将为此视图控制器提供某些东西?


问题答案:

简而言之-
@ComponentScan告诉Spring您在哪些包中带有应由Spring管理的带注释的类。因此,例如,如果您有一个带有注释的类,@Controller而该类在不被Spring扫描的软件包中,则您将无法将其用作Spring控制器。

带注释的类@Configuration是一种使用注释而不是XML文件配置Spring 的
方法(称为Java配置)。Spring需要知道哪些软件包包含spring
bean,否则您将不得不分别注册每个bean。那@ComponentScan就是用的。

在您的示例中,您告诉Spring程序包com.apress.prospringmvc.bookstore.web包含应由Spring处理的类。然后,Spring找到带有注释的类@Controller,并对其进行处理,这将导致所有请求都/index.htm被控制器拦截。

当请求被拦截时,Spring需要知道要发送给调用者的响应是什么。由于您返回的实例ModelAndView,因此它将尝试查找index项目中调用的视图(JSP页面)(其详细信息取决于配置的视图解析器),并将其呈现给用户。

如果@Controller没有注释,或者Spring没有扫描该软件包,那么所有这些都是不可能的。