2010-07-01 27 views
7

小糊塗,基本彈簧MVC應用程序具有這樣的:彈簧基本的MVC範例應用程序,註釋掃描混亂

應用-config.xml中

<context:component-scan base-package="org.springframework.samples.mvc.basic" /> 

和MVC-config.xml中具有:

<!-- Configures the @Controller programming model --> 
    <mvc:annotation-driven /> 
  1. 你真的需要兩個嗎?

  2. 組件掃描,這是否意味着如果我沒有把正確的包路徑我的@Controller和@Service標記將沒有任何影響? 如果我需要多個包裝,我只需複製條目?

我試着只用MVC:註解驅動,但沒有工作,我不得不把com.example.web.controllers在組件掃描XML節點,使其工作。

回答

11

方面:組件掃描顯然

掃描類路徑註釋組件將自動註冊如春豆默認情況下,將檢測到Spring提供的@Component,@Repository,@Service和@Controller原型。

所以@Controller只是一個Spring bean。沒有其他的。

而且

MVC:註解驅動

寄存器HandlerMapping的和需要的HandlerAdapter到派遣請求您@Controllers

這類似於

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> 

如果我需要一個以上的軟件包,我是否重複輸入?

你可以,如果你想。 上下文:組件掃描只是一個豆後處理器

<context:component-scan base-package="br.com.app.view.controller"/> 
<context:component-scan base-package="br.com.app.service"/> 

或者

用逗號分隔的包掃描標註的成分列表。

<context:component-scan base-package="br.com.app.view.controller,br.com.app.service"/> 
+1

只是出於好奇:背景:組件掃描包括AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor會,這意味着意味着兩個組件都會被自動檢測並連接在一起 - **無不在XML中提供任何bean配置元數據** – 2010-07-01 03:11:16

+0

謝謝,我不想做br.com.app,因爲它將會掃描潛在更多的課程而不是所需的課程。很好的回答!順便說一句什麼是@Component和@Service之間的差異? – Blankman 2010-07-01 04:02:23

+0

@Blankman無。 @Service也是一個@Component註釋。在這裏看到:http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/stereotype/Service.html這僅僅是一個特殊的元數據,以**表示在服務層中的服務組件* *。 – 2010-07-01 04:10:39

1
  1. mvc:annotation-driven允許您配置Spring MVC的行爲。詳見documentation。對於Spring MVC的基本用法,你不需要它。
  2. 如果你需要一個以上的包只提父之一:<context:component-scan base-package="org.springframework.samples.mvc" />
+0

所以有MVC:註解驅動的無所作爲? – Blankman 2010-07-01 02:26:34

+0

沒有,'MVC:註解driven'允許您配置Spring MVC的行爲。查看文檔http://static.springsource.org/spring/docs/3.0.3.RELEASE/spring-framework-reference/html/mvc.html#mvc-annotation-driven 細節對於Spring MVC的,你的基本用法不需要它。 – uthark 2010-07-01 02:32:51