SpringBoot注册Java Bean

====================================================================

IOC(Inversion Of Control,反转控制)是把对象的控制权较给框架或容器,容器中存储了众多我们需要的对象,然后我们就无需再手动的在代码中创建对象,即看不到new关键字。

需要什么对象就直接告诉容器我们需要什么对象,容器会把对象根据一定的方式注入到我们的代码中。
注入的过程被称为DI(Dependency Injection,依赖注入)。

有时候需要动态的指定我们需要什么对象,这个时候要让容器在众多对象中去寻找。
容器寻找需要对象的过程称为DL(Dependency Lookup, 依赖查找)。

Spring在启动时会把对象(这里指Bean对象)注册到ioc容器里,实现控制反转,开发过程中所有对象都从容器里获得,对象的生命周期受IOC控制。

  • 下面说一下三种注册bean的方法

    1. @ComponentScan
    2. @Bean
    3. @Import
@ComponentScan注册指定包里的bean
Spring容器会扫描@ComponentScan配置的包路径,找到标记以下标记的类加入到Spring容器。

我们经常用到的类似的(注册到IOC容器)注解有如下几个:

@Component
    配置类,当前类需要被组件扫描器扫描到并实例化对象到IOC容器
@Configuration
    配置类,当前类里面用@Bean注解需要被实例化到IOC容器中,范围更大
@Controller
    WEB控制器
@Repository
    数据仓库
@Service
    业务逻辑

例子:@Component指当前这类就是Bean,EmailLogServiceImpl注册到IOC中

@Component
public class EmailLogServiceImpl implements EmailLogService {

  @Override
  public void send(String email, String message) {
    Assert.notNull(email, "email must not be null!");
    logger.info("send email:{},message:{}", email, message);
  }
}

例子:@Configuration指@Bean方法作为一个Bean,可以有多个Bean,每个方法都需要有一个返回类型,而这个类型就是注册到IOC容器的类型,接口和类都是可以的,介于面向接口原则,提倡返回类型为接口。

@Configuration
public class LogServiceConfig {

  /**
   * 扩展printLogService行为,直接影响到LogService对象,因为LogService依赖于PrintLogService.
   *
   * @return
   */
  @Bean
  public PrintLogService printLogService() {
    return new PrintLogServiceImpl();
  }

  @Bean
  public EmailLogService emailLogService() {
    return new EmailLogServiceImpl();
  }

  @Bean
  public PrintLogService consolePrintLogService() {
    return new ConsolePrintLogService();
  }



}

例子:@Import直接把指定的类型注册到IOC容器里

@Import({ LogService.class,PrintService.class })
public class RegistryBean {

}