一、将javaBean装载到容器中的方式(注解版)
一、自定义的javabean装载到容器中
1.1、@ComponentScan+@Component
对于我们自己创建(自定义)的javabean,将它加入到Spring容器中,我们一般使用@ComponentScan+@Component注解的方式将它加到组件中。@ComponentScan的value属性指定包扫描路径,指定包及其子包下标注了@Component注解的Javabean会被加到容器中(注意:@Controller、@Service、@Repository本质上也是@Component,他们的作用本质是一样的)
示例:
1、配置类
/**
*
* @ComponentScan注解包扫描,会将指定包下标注了@Component、@Controller、@Service、@Resposity的组件加载到容器中去。
* 它有以下常用属性:
* 1、basePackages属性:指定要扫描的包
* 2、useDefaultFilters:是否使用默认的过滤器,默认是true。想自己指定过滤规则时要将该属性设置为false
* 3、includeFilters属性:指定满足被扫描的包下的组件要满足哪些条件才能被加到容器中,它是一个@Filter集合
* @Filter过滤注解。它的常用属性如下:
* 1、type属性指定根据什么条件过滤 1)FilterType.ANNOTATION根据注解类型过滤
* 2)FilterType.ASSIGNABLE_TYPE根据组件的类型过滤
* 3)FilterType.ASPECTJ根据ASPECTJ表达式过滤
* 4)FilterType.REGEX根据正则表达式过滤(基本不用、我也不太会)
* 5)FilterType.CUSTOM自定义过滤规则
* 4、excludeFilters属性:指定不将哪些包加入到容器中,用法和includeFilters属性差不多
*/
@ComponentScan(
basePackages={
"com.tellhow.review.spring_annotation.componenttocontainer"},
useDefaultFilters=false,
includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {
MyTypeFilter.class})}
)
@Slf4j
@Configuration//标注了@Configuration注解的类,Spring会将它识别为配置类。标注了@Configuration注解的类也会当做组件加到容器中
public class SpringAnnotationAddComponent {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
for (String beanDefinitionName : applicationContext.getBeanDefinitionNames()) {
log.info(beanDefinitionName);
}
}
}
//自定义类型过滤器,用来过滤不需要加到容器的组件
class MyTypeFilter implements TypeFilter {