Spring註解系列二:組件註冊-@ComponentScan

1、在配置類中配置包掃描

<!-- 包掃描、只要標註了@Controller、@Service、@Repository,@Component -->
<context:component-scan base-package="com.atguigu"></context:component-scan>
@Configuration  
@ComponentScan(value="com.atguigu")
public class MainConfig {
}

2、創建組件

@Controller
public class BookController {
}
@Service
public class BookService {
}
@Repository
public class BookDao {
}

3、創建測試方法

@SuppressWarnings("resource")
@Test
public void test01(){
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
	String[] definitionNames = applicationContext.getBeanDefinitionNames();
	for (String name : definitionNames) {
		System.out.println(name);
	}
}

在這裏插入圖片描述
4、包掃描時排除某些組件excludeFilters

@Configuration  
@ComponentScan(value="com.atguigu",excludeFilters = {
		@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
})
public class MainConfig {
}

在這裏插入圖片描述
5、包掃描時只包含某些組件includeFilters

//以前要只包含某些組件必須使用use-default-filters="false"禁用默認規則。默認是掃描所有的
<context:component-scan base-package="com.atguigu" use-default-filters="false"></context:component-scan> 
@Configuration  
@ComponentScan(value="com.atguigu",includeFilters = {
		@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
},useDefaultFilters = false)
public class MainConfig {
}

在這裏插入圖片描述
6、@ComponentScans註解

@Configuration 
@ComponentScans(value = @ComponentScan(value="com.atguigu",includeFilters = {
		@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
},useDefaultFilters = false))
public class MainConfig {
}

在這裏插入圖片描述
7、@ComponentScan可以重複標註

@ComponentScan(value="com.atguigu",excludeFilters = {
		@Filter(type=FilterType.ANNOTATION,classes={Service.class})
},useDefaultFilters = false)
@ComponentScan(value="com.atguigu",includeFilters = {
		@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
},useDefaultFilters = false)
public class MainConfig {
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章