VS

<annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in xml or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the the class specified contains methods that will handle http requests without you having to implement the Controller interface or extend a subclass that implements controller.

When spring starts up it reads its xml configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default spring assumes that all the classes it should manage are explicitly defined in the beans.xml file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the class path for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller , or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the xml configuration files.

In a typical spring mvc app you will find that there are two spring configuration files, a file that configures the application context, usually started with the spring context listener.

<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet> <servlet-name>main</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the spring mvc, the dispatches servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, jpa configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

你可能感兴趣的:( VS)