Sping注解开发

  基本注解

  @Configuration

  作用: 标记在类上表示是一个配置类(相当于一个配置类)

  @Bean

  作用: 在容器中放一个bean相当于xml文件里的bean标签

  @Configuration

  public class DemoConfig {

  @Bean

  public Person person(){

  Person person = new Person();

  person.setPerson("china");

  return person;

  }

  }

  @scope

  作用: 指定作用域

  

scope

  分为单例,多例等

  @ComponentScan()

  作用: 包扫描

  @Configuration

  @ComponentScan("com.zyh.pratice")

  public class DemoConfig {

  @Bean

  public Person person(){

  Person person = new Person();

  person.setPerson("china");

  return person;

  }

  }

  指定报下的注解都可以被扫描到

  过滤

  excludeFilters:不包含

  用法

  @Configuration

  @ComponentScan(value = "com.zyh.pratice", excludeFilters ={

  @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = IncludeBean.class),

  })

  public class DemoConfig {

  includeFilters:包含

  用法

  @Configuration

  @ComponentScan(value = "com.zyh.pratice", includeFilters ={

  @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = IncludeBean.class),

  },useDefaultFilters = false)

  注意 用includeFilters 时要将useDefaultFilters 设为false

  FilterType

  有这几种类型可选

  无锡妇科检查医院 http://www.87554006.com/

在这里插入图片描述

  @Conditional

  作用:条件注解,传入一个Condition的实现类,条件满足时才去加载bean

  @Conditional(ConditionDemo.class)

  public Bill bill(){

  return new Bill();

  }

  Condition

  作用位置

  被bean注释的方法上:满足条件时注册该bean

  类上:满足条件时注册该类

  import

  作用:导入指定的类

  @Configuration

  @ComponentScan

  @Import(ImportDemo.class)

  public class DemoConfig2 {

  }

  这样 ImportDemo就会被注册到容器中

  ImportSelector

  实现ImportSelector接口后,可以返回多个类,注册到容器中

  

ImportSelector

  

ImportSelector

  ImportBeanDefinitionRegistrar

  public class BeanDefinitionDemo implements ImportBeanDefinitionRegistrar {

  public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {

  BeanDefinition beanDefinition = new RootBeanDefinition(BeanDemo.class);

  beanDefinitionRegistry.registerBeanDefinition("beanDemo",beanDefinition);

猜你喜欢

转载自www.cnblogs.com/djw12333/p/11438983.html