在配置类中:
@Configuration //告诉spring这是个配置类
//扫描com.spring包下的@Service、@Controller、@Repository、@Component (interface文件加了注解注入不进去)
//也可定义过滤
@ComponentScan(value = "com.spring",excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class})
})
public class SpringConfig {
/**
* 给spring ioc中注册一个bean,返回值为类型,方法名为id
* 将返回值注入到容器中,方法名为组件id
*/
@Bean
public Person personTest(){
return new Person("小陈","22");
}
}
在xml文件中
<context:component-scan base-package="com.spring"></context:component-scan>
main方法测试
扩展:
@ComponentScan(value = "com.spring",excludeFilters = {
//根据注解扫描过滤
/* @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class}),*/
//根据给定类型过滤
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonService.class})
})
public class SpringConfig {
/**
* 给spring ioc中注册一个bean,返回值为类型,方法名为id
* 将返回值注入到容器中,方法名为组件id
*/
@Bean
public Person personTest(){
return new Person("小陈","22");
}
}
自定义注解扫描过滤:
@Configuration //告诉spring这是个配置类
//扫描com.spring包下的@Service、@Controller、@Repository、@Component (interface文件加了注解注入不进去)
//也可定义过滤
@ComponentScan(value = "com.spring",excludeFilters = {
//根据注解扫描过滤
/* @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class}),*/
//根据给定类型过滤
/*@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonService.class}),*/
//自定义注解
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyComponentFilter.class})
})
public class SpringConfig {
/**
* 给spring ioc中注册一个bean,返回值为类型,方法名为id
* 将返回值注入到容器中,方法名为组件id
*/
@Bean
public Person personTest(){
return new Person("小陈","22");
}
}
自己写个过滤类:
public class MyComponentFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
ClassMetadata classMetadata = metadataReader.getClassMetadata();
Resource resource = metadataReader.getResource();
String className = classMetadata.getClassName();
System.out.println("类名称:"+className);
//定义过滤规则,如果组件id名称中包含字母ce的过滤掉
if (className.contains("ce")){
return true;
}
return false;
}
}
main方法测试: