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 {
}