2017-09-15 57 views
0

我已經創建了一個基本的Spring MVC應用程序,當我XML配置這樣Spring的XML配置混合java的配置

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 

     xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context-4.3.xsd 
          http://www.springframework.org/schema/mvc 
          http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
" > 
    <context:component-scan base-package="com.hell"/> 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="prefix" value="/WEB-INF/pages/"/> 
     <property name="suffix" value=".jsp"/> 
    </bean> 

</beans> 

一切順利的話,控制器和通過@RequestMapping映射視圖,但是當我添加此空類和構建

@Configuration 
public class Config { 
} 

路由不起作用,它說404錯誤。 然後我必須添加<mvc:annotation-config/>@EnableWebMVC,然後路由工作。
有人可以解釋這一點,我覺得這很奇怪。
編輯: 這是我的web.xml中配置的DispatcherServlet

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

如果您真的想要混合使用兩種配置樣式,那麼您可以使用「ConfigurationPostProcessor」從XML引導您的JavaConfig。 – Matt

回答

0

我在網上搜索,我發現context:component-scan告訴Spring來掃描@Configuration類,所以也許這就是答案我問題,任何人都請糾正我。

0

@Configuration用於基於Java的spring配置,所以我認爲如果你通過Java代碼來配置你的bean,那麼你的xml配置是有限的。我會建議堅持一種方法,這將使你的代碼容易to.maintain

+0

是的,我剛剛學習Spring,想嘗試一切, 但在我的例子中,Spring不需要'mvc:annotation-driven'來映射視圖,但是當使用'@ Configuration'時它需要' mvc:註解驅動'運行 – halo88