注解扫描
<context:component-scan base-package="org.bdp">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
该方式下的,不仅会扫描controoler层,同时会扫描@service和@repository的bean,此时会出现一些问题 这个尤其在springmvc+spring+hibernate等集成时最容易出问题的地,最典型的错误就是:
为了避免该情况的发生,可以添加use-default-filters="false"
即:
<context:component-scan base-package="org.bdp" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
原因解析:
查看源码
protected void registerDefaultFilters() { this.includeFilters.add(new AnnotationTypeFilter(Component.class)); ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader(); try { this.includeFilters.add(new AnnotationTypeFilter(ClassUtils.forName("javax.annotation.ManagedBean", cl), false)); this.logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning"); } catch (ClassNotFoundException var4) { ; } try { this.includeFilters.add(new AnnotationTypeFilter(ClassUtils.forName("javax.inject.Named", cl), false)); this.logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning"); } catch (ClassNotFoundException var3) { ; }}
可以知道,在扫描的时候会默认去扫描component Named。ManagedBean等的注解
@service等注解
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { String value() default ""; }
可以清楚的观察到@service注都是@component
原因找到以后:解决办法就是关闭使用默认的过滤器