springboot~注冊bean的方法
spring在啟動時會自己把bean(java組件)注冊到ioc容器里,實現控制反轉,在開發人員使用spring開發應用程序時,你是看不到new關鍵字的,所有對象都應該從容器里獲得,它們的生命周期在放(fang)入(ru)容器時已經(jing)確(que)定!
下(xia)面說(shuo)一下(xia)三種(zhong)注冊bean的(de)方法(fa)
- @ComponentScan
- @Bean
- @Import
@ComponentScan注冊指定包里的bean
Spring容(rong)器(qi)會掃(sao)描@ComponentScan配(pei)置的包路徑,找到(dao)標記@Component注解(jie)的類加入到(dao)Spring容(rong)器(qi)。
我們經常用到(dao)的(de)類似的(de)(注(zhu)冊到(dao)IOC容器)注(zhu)解還(huan)有如下幾個:
- @Configuration:配置類
- @Controller :web控制器
- @Repository :數據倉庫
- @Service:業務邏輯
下面(mian)代碼完成了EmailLogServiceImpl這個bean的(de)注冊,當然(ran)也可以放在@Bean里(li)統一注冊,需要看@Bean那一節里(li)的(de)介(jie)紹。
@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被聲明在方(fang)法(fa)上,方(fang)法(fa)都需要(yao)有一個(ge)返回類(lei)型,而這個(ge)類(lei)型就是(shi)注冊到(dao)IOC容器的類(lei)型,接口(kou)和類(lei)都是(shi)可(ke)以的,介于(yu)面向接口(kou)原則,提倡(chang)返回類(lei)型為(wei)接口(kou)。
下面代碼在一個@Configuration注解(jie)的類(lei)中,同時注冊了多個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
這(zhe)種方法最為直接,直接把(ba)指定的類型注(zhu)冊(ce)(ce)到IOC容器里,成為一個java bean,可(ke)以把(ba)@Import放(fang)在(zai)程序(xu)的八口(kou),它在(zai)程序(xu)啟動時自(zi)動完(wan)成注(zhu)冊(ce)(ce)bean的過程。
@Import({ LogService.class,PrintService.class })
public class RegistryBean {
}
Spring之所(suo)以如(ru)何受歡迎,我想很大原因是它自(zi)動化注(zhu)冊(ce)和自(zi)動化配置這(zhe)一塊(kuai)的(de)(de)設計(ji),確實讓開發人員(yuan)感(gan)到非(fei)常(chang)的(de)(de)自(zi)如(ru),.net里也有類似的(de)(de)產(chan)品,像(xiang)近幾年比(bi)較流行的(de)(de)abp框(kuang)(kuang)架,大叔(shu)自(zi)己(ji)也寫過(guo)類似的(de)(de)lind框(kuang)(kuang)架,都是基于自(zi)動化注(zhu)冊(ce)和自(zi)動化配置的(de)(de)理念。