@ComponentScan配置了excludeFilters不扫描controller但是扫描了

最近在做 去掉web.xml和applicationcontex.xml配置文件。

也就是基于javaConfig配置,阅读起来更易读

明明配置了 root contex过滤掉controller,但是任然扫描到controller。

@Configuration//表示配置类
@ComponentScan(basePackages={"springstudy.controller"},
includeFilters={@Filter(type=FilterType.ANNOTATION,classes={Controller.class})},useDefaultFilters=false)
//扫描springstudy.controller包并且只扫描controller注解,不适用默认的过滤规则
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

	/**
	 * 
	-Xms320m -Xmx320m -XX:+PrintGCDetails -XX:+UseSerialGC
	 */
	
	
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
	
	@Bean
	public ViewResolver viewResolver(){
		InternalResourceViewResolver viewResolver = 
				new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/jsp/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}


//扫描springstudy包,不扫描controller注解,但是一直都会扫描到?
//原因是只是过滤了controller注解,但是会扫描到上面的WebConfig 类也就是会扫描controller
//正确的配置是value={Controller.class,WebConfig.class}
@ComponentScan(basePackages={"springstudy"},excludeFilters={@Filter(type=FilterType.ANNOTATION,value={Controller.class})})
@Configuration
public class RootConfig {
	
}

同时 spring还支持自定义过滤器。过滤你要的结果

只需要实现TypeFilter接口

package springstudy.config;

import java.io.IOException;

import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

public class MyFilter implements TypeFilter {


	public boolean match(MetadataReader metadataReader, MetadataReaderFactory arg1) throws IOException {
		 ClassMetadata classMetadata = metadataReader.getClassMetadata();
		 System.out.println(classMetadata.getClassName());
		return classMetadata.getClassName().contains("Controller");
	}
}

 

你可能感兴趣的:(spring,in,action学习,@ComponentScan,spring注解)