Spring Boot Bean和依賴注入
在Spring Boot中,可以使用Spring Framework來定義bean及其依賴注入。 [@ComponentScan](https://github.com/ComponentScan "@ComponentScan")
註釋用於查找bean
以及使用[@Autowired](https://github.com/Autowired "@Autowired")
註釋注入的相應內容。
如果遵循Spring Boot典型佈局,則無需爲[@ComponentScan](https://github.com/ComponentScan "@ComponentScan")
註釋指定任何參數。 所有組件類文件都自動註冊到Spring Beans。
以下示例提供了有關自動連接Rest Template對象併爲其創建Bean代碼片段 -
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
以下代碼顯示主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();
}
}
0 條評論,你可以發表評論,我們會進行改進
