2017-10-09 58 views
0

我想了解從Spring使用xml註釋到基於java的批註的過渡。我有這些定義:什麼是您將在Spring中使用@Configuration和@ComponentScan的特定用例?

<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml. 

<context:component-scan>: Bean registration + <context:annotation-config> 

是@Configuration並且是@ComponentScan。

如果我們說我用@Component聲明瞭所有的bean(首先忽略@Repository,@Service等更具體的註釋)註釋,並確保包由@ComponentScan註釋掃描,那麼什麼是特定的用例,我仍然會用@ComponentScan和@Configuration來註釋我的類。

我問這個問題,因爲有時候我看到類同時用@Configuration和@ComponentScan註解。

回答

1

首先仔細閱讀以下內容:

Difference between <context:annotation-config> vs <context:component-scan>

因此<context:component-scan>是否掃描工作同樣的工作比<context:annotation-config>確實,這意味着工作與DI註釋

然後圍繞現在考慮:

  • <context:component-scan>相當於@ComponentScan
  • <context:annotation-config>沒有用於註釋的等價物。

什麼是特定使用情況下我仍然會與兩個@Configuration標註我的課 連同@ComponentScan?

@Configuration用於定義約InfastructureDatabaseJMS等豆類...

是的,一類可以同時使用,它可以被用於例如MVC架構@Configuration如:

@EnableWebMvc 
@Configuration 
@ComponentScan("com.manuel.jordan.controller", "com.manuel.jordan.rest") 
public class WebMvcConfig extends WebMvcConfigurerAdapter { 

因此,從該類您正在配置MVC,只表示掃描您爲「網絡端」創建的MVC類,例如:@Controller,@RestController

+0

對於註釋沒有等價物。這一個幫助,一直以來我認爲@Configuration是相當於的java註釋 –

0

這真的取決於你的喜好和編碼風格。文檔狀態:

可以指定basePackageClasses()或basePackages()(或其別名value())來定義要掃描的特定軟件包。如果未定義特定的包,則將從聲明此批註的類的包中進行掃描。

因此,每次只看到@ComponentScan註釋,這意味着應掃描所有子包。對於每個功能部件包的佈局,這是一種合理的方法:當您的功能部件有@Configuration類,並且所有@Components都與子包中的功能相關時。

相關問題