spring注解---@ComponentScan注解 自动扫描

1 背景:在通过配置文件扫描bean到IOC容器的时候,需要的步骤。

           1.1 给相应的了加上@Controller @Repository @Service @Component注解

            1.2  在bean.xml文件中编写<context:component-scan>标签。这样有注释的类才会被扫描到IOC容器中。

<context:component-scan base-package="com.componentscan"></context:component-scan>

2 通过注解的方式。 @ComponentScan注解

@ComponentScan(value="com.componentscan",
               excludeFilters= {
            		   @Filter(type=FilterType.ANNOTATION,classes= {Controller.class,Service.class})	
})
public class ConfigTest {
	@Bean(value="person01")
	public Person person111() {
		return new Person("haha", 100);
	}
}

     2.1 value : 指定需要扫描的包。

     2.2 excludeFilters :按照某些规则,排除某些资源。

                写法:excludeFiltersincludeFilters里面是通过@Filter注解来指定包含或者排除的规则。

                            type:FilterType 来指定排除或者包含资源的方式

                                       FilterType的介绍

                            classes:来指定要排除的类。

                解释:例子中的意思是,按照注解的来排除资源,排除的资源是标注了@Controller和@Service的类不会被扫描到IOC中。

    2.3 includeFilters: 按照某些规则,包含某些资源。

@Configuration
@ComponentScan(value = "com.componentscan", useDefaultFilters = false,
               includeFilters = { 
		@Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class }) })

public class ConfigTest {
	@Bean(value = "person01")
	public Person person111() {
		return new Person("haha", 100);
	}
}

                 写法:同excludeFilters写法。

                 注意: 如果要使用includeFilters 的话,需要配合useDefaultFilters 参数,禁用后,自己设置的包含规则才能生效。

  2.4 useDefaultFilters :是否使用默认规则。通常和 includeFilters 参数配合使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章