2013-04-26 80 views
32

我想在Spring中從基於XML的配置切換到基於Java的配置。現在,我們有這樣的事情在我們的應用程序上下文:過濾@ComponentScan中的特定軟件包

<context:component-scan base-package="foo.bar"> 
    <context:exclude-filter type="annotation" expression="o.s.s.Service"/> 
</context:component-scan> 
<context:component-scan base-package="foo.baz" /> 

但如果我寫這樣的事情...

@ComponentScan(
    basePackages = {"foo.bar", "foo.baz"}, 
    excludeFilters = @ComponentScan.Filter(
     value= Service.class, 
     type = FilterType.ANNOTATION 
    ) 
) 

...它將從包排除服務。我有強烈的感覺,我忽略了一些令人尷尬的微不足道的事情,但我找不到解決方案將過濾器的範圍限制爲foo.bar

回答

38

您只需要爲您需要的兩個@ComponentScan註釋創建兩個Config類。實例你Spring上下文時

@Configuration 
@ComponentScan(basePackages = {"foo.baz"}) 
public class FooBazConfig { 
} 

則:

因此,例如,你將有一個Config類爲您foo.bar包:

@Configuration 
@ComponentScan(basePackages = {"foo.bar"}, 
    excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION) 
) 
public class FooBarConfig { 
} 

,然後第2個Config類爲您foo.baz包將執行以下操作:

new AnnotationConfigApplicationContext(FooBarConfig.class, FooBazConfig.class); 

另一種方法是,您可以使用第一個Config類中的@org.springframework.context.annotation.Import註釋導入第二個Config類。因此,例如,你可以改變FooBarConfig是:

new AnnotationConfigApplicationContext(FooBarConfig.class) 
+0

發生'Service.class'什麼:

@Configuration @ComponentScan(basePackages = {"foo.bar"}, excludeFilters = @ComponentScan.Filter(value = Service.class, type = FilterType.ANNOTATION) ) @Import(FooBazConfig.class) public class FooBarConfig { } 

,那麼只需在下手的情況下? – Deepen 2016-06-25 07:26:20

相關問題