context:component-scan配置策略
Spring applicationContext.xml的<context:component-scan>用途比我想像的要用。而且後才知道,有了<context:component-scan>,另一<context:annotation-config/>根本可以移除掉,因被包含去了。原本我survery Spring3通常只配置成<context:component-scan base-package="com.foo.bar"/>,意即在base-package下找有@Component和@Configuration的target Class。而在如下的粒:
<context:component-scan base-package="com.foo" use-default-filters="false">
??? <context:include-filter type="regex" expression="com.foo.bar.*Config"/>
??? <context:include-filter type="regex" expression="com.foo.config.*"/>
</context:component-scan>
<context:component-scan>提供子:<context:include-filter>和<context:exclude-filter>各代表引入和排除的。而上例把use-default-filters性false,意即在base-package所有被宣告@Component和@Configuration等target Class不予bean,由filter子代。
filter在Spring3有五type,如下:
Filter TypeExamples ExpressionDescriptionannotationorg.example.SomeAnnotation符合SomeAnnoation的target classassignableorg.example.SomeClass指定class或interface的全名aspectjorg.example..*Service+AspectJ法regexorg\.example\.Default.*Regelar Expressioncustomorg.example.MyTypeFilterSpring3新增自Type,作org.springframework.core.type.TypeFilter所以上例用的regex就有病,com.foo.config.* 可以找到com.foo.config.WebLogger,但也可以找到com1fool2config3abcde,因小在Regex是任意字元,是故要用\.把小跳佳。(2010/3/15充:但要使用\.方式,其use-default-filters不能false,否抓不到,感是Bug)
Spring3提供富的Filter支援,有益配置策略,不需面Configuration Hell,比如Regex的com\.foo\.*\.action\.*Config,就可以找到com.foo package下所有action子package的*Config的target class。
2010/3/18充:後在AppConfig前忘了加@Component,AppConfig尚留有@Bean,奇怪的是是能work。我猜有加@Bean的method的class,若特解AppConfig是@Repository、@Service是@Configuration,一律被Spring3@Component。
1 楼 Lshine 2011-09-14 到处都是这篇的转载 就是因为你们这样的人太多 搞得互联网到处都是垃圾.