SpringBoot(三):注解汇总

一、注解汇总

  @Component   类注解,标明哪个类扫描到 IOC 容器中

  @ComponentScan   标明使用何种策略扫描类到容器中

  @Value   指定类中属性的值,在装在IOC的时候,会赋值

  @Primary  同一个接口有多个实现的时候,指定默认的实现类

  @Qualifier  同一个接口有多个实现类的时候,通过 type 和 name 来确认实现类,name 在Spring Ioc 中是唯一的

  @ConfigurationProperties  读取properties文件时,通过key的前缀,批量赋值

  @PropertySource  指定properties文件,可以指定多个

  @Conditional

  @Profile  

  @ActiveProfile

  @ImportResource  引入 xml 配置 bean ,注解位置在SpringBoot 入口类

 

 

二、注解详解

  1、@Component

    @Component("name") name是容器中名称

 

  2、@ComponentScan

     @ComponentScan  默没有指定属性,默认扫描当前类所在的包以及子包,在使用时,可以指定属性,有如下属性

    basePackages : 定义扫描的包

    basePackageClasses : 定义扫描的类

    includeFilters : 定义满足filter的类才被扫描

    excludeFilters : 排除过滤条件的bean

    lazyInit : Boolean型,默认FALSE,启动的时候初始化bean ,true 第一次使用的时候初始化bean

@ComponentScan("com.springboot.chapter3.*")
@ComponentScan(basePackages = {"com.springboot.chapter3.pojo"})
@ComponentScan(basePackageClasses = {User.class})

  @ComponentScan(basePackages = {"com.springboot.chapter3"},excludeFilters = {@Filter(classes = Service.class)})

  

  3、@Primary 和 @Qualifier

    @Autowired 是通过 type 找到 bean 进行依赖,如果接口有多个实现(例如动物的实现有猫、狗),如果不指定具体某个实现类,依赖会出错。@Primary 在定义接口实现类的时候添加,标示默认选定。@Qualifier 结合 @Autowired 使用,在依赖的时候,@Qualifer("beanName"),就能唯一定位到指定的实现类。消除歧义性。

@Autowired
@Qualifier("dog")
private Animal animal = null;


/** 带有参数的装配 */
public BussinessPerson(@Autowired @Qualifier("dog") Animal animal) {
  this.animal = animal;
}

 

  4、@ConfigurationProperties  自动组装properties文件中的key,规则:@ConfigurationProperties("key1") ,key1 + 属性名,例如database.url

@Component
@ConfigurationProperties("database")
public class DataBaseProperties {
    
     private String driverName = null;
     private String url = null;
     private String username = null;
     private String password = null;
     
 ...
}

 

  5、PropertySource

  value可以配置多个配置文件。使用classpath前缀,意味着去类文件路径下找到属性文件;ignoreResourceNotFound则是是否忽略配置文件找不到的问题。ignoreResourceNotFound的默认值为false,没找到配置文件报错

@SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.chapter3"})
@PropertySource(value={"classpath:jdbc.properties"}, ignoreResourceNotFound=true)
public class Chapter3Application {
 public static void main(String[] args) {
     SpringApplication.run(Chapter3Application.class, args);
 }
}

 

posted @ 2018-10-07 22:45  刘广平  阅读(359)  评论(0)    收藏  举报