2013-08-30 64 views
10

每個Spring 3文檔,The IoC container@Named註釋是一個等效於@Component註釋的標準。@ Spring MVC中的註釋名稱

由於@Repository@Service@Controller都是@Component,我試圖用@Named對所有的人都在我的Spring MVC應用程序。它工作正常。但我發現@Controller的替代似乎有一個錯誤。在控制器類,原來,它是

@Controller 
public class MyController{ 
    ... 
} 

它工作正常。當我改變@Controller@Named

@Named 
public class MyController{ 
    ... 
} 

它失敗,出現錯誤:

"No mapping found for HTTP request with URI ...".

但如果我說@RequestMapping以班級爲遵循

@Named 
@RequestMapping 
public class MyController{ 
    ... 
} 

預期它的工作。

對於@Repository@Service,我可以簡單地將它們替換爲@Named而沒有問題。但更換@Controller需要額外的工作。在配置中有什麼我缺少的東西?

回答

16

@Named@Component的作用相同。但是,註釋@Controller,@Service@Repository更具體。

從春docs

@Component is a generic stereotype for any Spring-managed component. @Repository , @Service , and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository , @Service , and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

This部分解釋了@Named的差異。

很多組件,比如Spring的DispatcherServlet(在WebApplicationContext MVC配置)是不是在找Component,他們正在尋找@Controller。所以當它掃描你的課程時,它不會在@Named中找到它。以類似的方式,@Transactional的交易管理尋找@Service@Repository,而不是更通用的@Component

+0

這是否意味着我可以放心地使用'@ Named'爲通用bean注入替換'@ Component',但是我仍然需要在Spring MVC特性中使用'@ Repository','@ Service'和'@ Controller'? –

+0

@dino歡迎您。考慮接受這個答案,除非你想等待更多的答案和其他細節。 –

3

所有@Repository@Service@Controller主要用於聲明Spring bean的,除了它提供了額外的信息,關於春天像控制器bean的類型,DAO等