springboot~注冊bean的方法


spring在啟動時會自己把bean(java組件)注冊到ioc容器里,實現控制反轉,在開發人員使用spring開發應用程序時,你是看不到new關鍵字的,所有對象都應該從容器里獲得,它們的生命周期在放入容器時已經確定!

下面說一下三種注冊bean的方法

  1. @ComponentScan
  2. @Bean
  3. @Import

@ComponentScan注冊指定包里的bean

Spring容器會掃描@ComponentScan配置的包路徑,找到標記@Component注解的類加入到Spring容器。

我們經常用到的類似的(注冊到IOC容器)注解還有如下幾個:

  • @Configuration:配置類
  • @Controller :web控制器
  • @Repository :數據倉庫
  • @Service:業務邏輯

下面代碼完成了EmailLogServiceImpl這個bean的注冊,當然也可以放在@Bean里統一注冊,需要看@Bean那一節里的介紹。

@Component
public class EmailLogServiceImpl implements EmailLogService {
  private static final Logger logger = LoggerFactory.getLogger(EmailLogServiceImpl.class);

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

@Bean注解直接注冊

注解@Bean被聲明在方法上,方法都需要有一個返回類型,而這個類型就是注冊到IOC容器的類型,接口和類都是可以的,介於面向接口原則,提倡返回類型為接口。

下面代碼在一個@Configuration注解的類中,同時注冊了多個bean。

@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注冊Bean

這種方法最為直接,直接把指定的類型注冊到IOC容器里,成為一個java bean,可以把@Import放在程序的八口,它在程序啟動時自動完成注冊bean的過程。

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

}

Spring之所以如何受歡迎,我想很大原因是它自動化注冊和自動化配置這一塊的設計,確實讓開發人員感到非常的自如,.net里也有類似的產品,像近幾年比較流行的abp框架,大叔自己也寫過類似的lind框架,都是基於自動化注冊和自動化配置的理念。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM