在Spring Boot中,可以使用Spring Framework來定義bean及其依賴注入。 @ComponentScan
注釋用於查找bean
以及使用@Autowired
注釋注入的相應內容。
如果遵循Spring Boot典型佈局,則無需為@ComponentScan
注釋指定任何參數。 所有組件類檔都自動註冊到Spring Beans。
以下示例提供了有關自動連接Rest Template對象並為其創建Bean代碼片段 -
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
以下代碼顯示主Spring Boot Application類檔中自動連接的Rest Template對象和Bean創建對象的代碼 -
package com.zaixian.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();
}
}
上一篇:
Spring Boot代碼結構
下一篇:
Spring Boot運行器(Runner)