Spring注解驱动开发

组件添加

  1. @ComponentScan:定义包扫描路径
    1. value:默认,扫描路径
    2. excludeFilters:排除扫描指定组件
    3. includeFilters:只扫描指定组件
    4. useDefaultFilters:使用默认扫描组件(在指定includeFilters时,该值必须设置为false,否者无效)
    5. @Filter:type 1. ANNOTATION(注解),ASSIGNABLE_TYPE(通过类型),ASPECTJ(切面),REGEX(正则),CUSTOM(自定义)
@ComponentScan(value = "com.ralap.spring",
//        excludeFilters = {
//                @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {Student.class}
//                )
//        includeFilters = {
//                @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {Student.class})}
//        , useDefaultFilters = false
        excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = {MyFilterType.class})}
)



public class MyFilterType implements TypeFilter {

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory         metadataReaderFactory)
            throws IOException {

        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        System.out.println(classMetadata.getClassName()+"-------");
        //添加类名包含Student
        if (classMetadata.getClassName().contains("Student")) {
            return true;
        }
        return false;
    }
}
  1. @Import 组件添加
    @Import({Dog.class, Cat.class, MyImportSelect.class,MyImportBeanRegistrar.class})
    
    1. 实现ImportSelector
     public class MyImportSelect implements ImportSelector {
    
        @Override
        public String[] selectImports(AnnotationMetadata annotationMetadata) {
            return new String[]{"com.ralap.spring.Monkey"};
        }
    }
    
    1. 实现ImportBeanDefinitionRegistrar
       public class MyImportBeanRegistrar implements ImportBeanDefinitionRegistrar {
    
      @Override
      public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
             BeanDefinitionRegistry beanDefinitionRegistry) {
          //Checken是指定添加组件
          RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Checken.class);
          beanDefinitionRegistry.registerBeanDefinition("checken",rootBeanDefinition);
      }
    }
    
  2. @Configuration 配置
  3. @Bean
    1. initMethod(对象创建后立即调用),destroyMethod(对象销毁前调用)
    2. 实现InitializingBean, DisposableBean
    3. @PostConstruct,@PreDestroy

初始化执行顺序 constructor--->postConstruct--->InitializingBean--->initMethod

  1. 后置处理器
    实现BeanPostProcessor
    postProcessBeforeInitialization 初始化前执行
    postProcessAfterInitialization初始化后执行

你可能感兴趣的:(Spring注解驱动开发)