springmvc <mvc:annotation-driven>和<context:component-scan base-package =“”>

时间:2018-05-24 06:06:11

标签: java spring spring-mvc

我有一个Spring + SpringMVC演示,当我在spring-mvc.xml中没有<mvc:annotation-driven/>时,我无法理解如何使用<context:component-scan base-package="com.jiehang.spring.controller"。项目也可以运行,如果是这样,为什么我们需要在spring-mvc.xml中编写<mvc:annotation-driven/>?有人可以回答我。感谢

的web.xml

<mvc:annotation-driven/>

弹簧mvc.xml:

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

spring.xml:

<context:component-scan base-package="com.jiehang.spring.controller" />
<!-- <mvc:annotation-driven /> -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

控制器:

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thinXXX" />
        <property name="username" value="XXX" />
        <property name="password" value="XXX" />
    </bean>

    <bean id="tsmCountsService" class="com.jiehang.spring.service.impl.TsmCountsServiceImpl">
        <property name="tsmCountsDao" ref="tsmCountsDao" />
    </bean>

    <bean id="tsmCountsDao" class="com.jiehang.spring.dao.impl.TsmCountsDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

当我输入url:http://localhost:8080/TestSpringmvc/queryFund时,我可以获得输出结果。所以,如果你不写@Controller public class FundController { @Autowired private TsmCountsService tsmCountsService; public TsmCountsService getTsmCountsService() { return tsmCountsService; } public void setTsmCountsService(TsmCountsService tsmCountsService) { this.tsmCountsService = tsmCountsService; } @RequestMapping("/queryFund") public ModelAndView queryFundByFundId() { List<TsmCounts> funds = tsmCountsService.queryUser(); System.out.println(funds); return null; } } 就没关系。

1 个答案:

答案 0 :(得分:0)

<mvc:annotation-driven />提供对注释驱动的MVC控制器(如@RequestMapping和@Controller)的支持,尽管它是默认行为,同时它通过@Valid和带有@RequestBody / ResponseBody的消息体增加了对验证的支持