springboot注冊bean的三種方法
spring在啟動時會自己把bean(java組件)注冊到ioc容器里,實現(xiàn)控制反轉(zhuǎn),在開發(fā)人員使用spring開發(fā)應(yīng)用程序時,你是看不到new關(guān)鍵字的,所有對象都應(yīng)該從容器里獲得,它們的 生命周期 在放入容器時已經(jīng)確定!
下面說一下三種注冊bean的方法
- @ComponentScan
- @Bean
- @Import
@ComponentScan注冊指定包里的bean
Spring容器會掃描@ComponentScan配置的包路徑,找到標(biāo)記@Component注解的類加入到Spring容器。
我們經(jīng)常用到的類似的(注冊到IOC容器)注解還有如下幾個:
- @Configuration:配置類
- @Controller :web控制器
- @Repository :數(shù)據(jù)倉庫
- @Service:業(yè)務(wù)邏輯
下面代碼完成了EmailLogServiceImpl這個bean的注冊,當(dāng)然也可以放在@Bean里統(tǒng)一注冊,需要看@Bean那一節(jié)里的介紹。
@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之所以如何受歡迎,我想很大原因是它自動化注冊和自動化配置這一塊的設(shè)計,確實讓開發(fā)人員感到非常的自如,.net里也有類似的產(chǎn)品,像近幾年比較流行的abp框架,大叔自己也寫過類似的lind框架,都是基于自動化注冊和自動化配置的理念。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot JS-SDK自定義微信分享的實現(xiàn)
這篇文章主要介紹了SpringBoot JS-SDK自定義微信分享的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Java中Integer的parseInt和valueOf的區(qū)別詳解
這篇文章主要介紹了Java中Integer的parseInt和valueOf的區(qū)別詳解,nteger.parseInt(s)是把字符串解析成int基本類型,Integer.valueOf(s)是把字符串解析成Integer對象類型,其實int就是Integer解包裝,Integer就是int的包裝,需要的朋友可以參考下2023-11-11