轉(zhuǎn):http://www.itdecent.cn/p/170cf6c36dce
1、在配置類中配置包掃描
<!-- 包掃描、只要標(biāo)注了@Controller、@Service、@Repository,@Component -->
<context:component-scan base-package="com.atguigu"></context:component-scan>
@Configuration
@ComponentScan(value="com.atguigu")
public class MainConfig {
}
2、創(chuàng)建組件
@Controller
public class BookController {
}
@Service
public class BookService {
}
@Repository
public class BookDao {
}
3、創(chuàng)建測(cè)試方法
@SuppressWarnings("resource")
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}

圖片.png
4、包掃描時(shí)排除某些組件excludeFilters
@Configuration
@ComponentScan(value="com.atguigu",excludeFilters = {
@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
})
public class MainConfig {
}

圖片.png
5、包掃描時(shí)只包含某些組件includeFilters
//以前要只包含某些組件必須使用use-default-filters="false"禁用默認(rèn)規(guī)則。默認(rèn)是掃描所有的
<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 {
}

圖片.png
6、@ComponentScans注解
@Configuration
@ComponentScans(value = @ComponentScan(value="com.atguigu",includeFilters = {
@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
},useDefaultFilters = false))
public class MainConfig {
}

圖片.png
7、@ComponentScan可以重復(fù)標(biāo)注
@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 {
}