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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…