在SpringBoot中,我们可以使用Spring Framework来定义我们的beans和它们的依赖注入,使用@ComponentScan注解来查找bean,以及使用@Autowired注解来自动注入相应的内容。
如果你使用SpringBoot的经典布局,就不需要对@ComponentScan注解指定任何参数,所有的组件类都会被自动注册到Spring容器中的Bean.
以下示例提供了有关自动连接Rest Template(Spring client访问Rest)对象并为其创建bean:
1 | Bean |
下面展示的是通过自动装配Rest Template对象以及Bean注入注解:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import 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;
public class DemoApplication {
RestTemplate restTemplate;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
评论加载中