spring在啓動時會本身把bean(java組件)註冊到ioc容器裏,實現控制反轉,在開發人員使用spring開發應用程序時,你是看不到new關鍵字的,全部對象都應該從容器裏得到,它們的生命週期
在放入容器時已經肯定!java
下面說一下三種註冊bean的方法web
Spring容器會掃描@ComponentScan配置的包路徑,找到標記@Component註解的類加入到Spring容器。spring
咱們常常用到的相似的(註冊到IOC容器)註解還有以下幾個:框架
下面代碼完成了EmailLogServiceImpl這個bean的註冊,固然也能夠放在@Bean裏統一註冊,須要看@Bean那一節裏的介紹。ide
@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被聲明在方法上,方法都須要有一個返回類型,而這個類型就是註冊到IOC容器的類型,接口和類都是能夠的,介於面向接口原則,提倡返回類型爲接口。.net
下面代碼在一個@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(); } }
這種方法最爲直接,直接把指定的類型註冊到IOC容器裏,成爲一個java bean,能夠把@Import放在程序的八口,它在程序啓動時自動完成註冊bean的過程。code
@Import({ LogService.class,PrintService.class }) public class RegistryBean { }
Spring之因此如何受歡迎,我想很大緣由是它自動化註冊和自動化配置這一塊的設計,確實讓開發人員感到很是的自如,.net裏也有相似的產品,像近幾年比較流行的abp框架,大叔本身也寫過相似的lind框架,都是基於自動化註冊和自動化配置的理念。component