如何理解春季@ComponentScan

2022-09-01 22:56:22

我正在学习有关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");    
    }    
}     

我的问题是,对于视图控制器,通过添加 和 ,将在后台执行哪些操作?该软件包会为这些视图控制器提供一些东西吗?@Configuration@ComponentScan(basePackages = { "com.apress.prospringmvc.bookstore.web" })com.apress.prospringmvc.bookstore.web


答案 1

简单地说 - 告诉Spring你在哪些包中注释了应该由Spring管理的类。因此,例如,如果您有一个带有注释的类,该类位于Spring未扫描的包中,则无法将其用作Spring控制器。@ComponentScan@Controller

用 注释的类是一种使用注释而不是XML文件配置Spring的新方法(它称为Java配置)。Spring需要知道哪些包包含spring bean,否则你必须单独注册每个bean。这就是用途。@Configuration@ComponentScan

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

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

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


答案 2

推荐