Spring Boot Bean和依賴注入


在Spring Boot中,可以使用Spring Framework來定義bean及其依賴注入。 @ComponentScan注釋用於查找bean以及使用@Autowired注釋注入的相應內容。

如果遵循Spring Boot典型布局,則無需為@ComponentScan注釋指定任何參數。 所有組件類文件都自動注冊到Spring Beans。

以下示例提供了有關自動連接Rest Template對象並為其創建Bean代碼片段 -

@Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } 
Java

以下代碼顯示主Spring Boot Application類文件中自動連接的Rest Template對象和Bean創建對象的代碼 -

package com.yiibai.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class DemoApplication { @Autowired RestTemplate restTemplate; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }


免責聲明!

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



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