1. 程式人生 > >springboot物件注入IOC容器的三種方式

springboot物件注入IOC容器的三種方式

Springboot會自動載入resources檔案下面的application.yml或者application.properties配置檔案,因為yml格式可以替代xml格式,功能properties更強大,所以一般都使用yml格式進行書寫。

1.對於yml中載入了的bean,可以使用 @value(${物件}) 進行注入。

2.也可以在需要加入到spring容器中的類上加@Component註解和@ConfigurationProperties(prefix="物件名"),將application.yml中的物件注入到Spring的IOC容器當中,在程式碼實際使用的時候可以通過@Autowired註解將物件注入。

3.可以使用@Configuration、@PropertySource(value="classpath:test.properties")、@ConfigurationProperties(prefix="com.hthl")這三個註解將resources檔案下test.properties描述的物件注入到ioc容器當中。