关于springboot:Spring-Boot快速入门之七Bean和依赖注入

4次阅读

共计 966 个字符,预计需要花费 3 分钟才能阅读完成。

【注】本文译自:https://www.tutorialspoint.com/spring_boot/spring_boot_beans_and_dependency_injection.htm

在 Spring Boot 中,咱们能够利用 Spring Framework 定义 bean 及其依赖注入。@ComponentScan 及其对应的 @Autowired 注解被用于发现和注入 bean。

如果你遵循典型的 Spring Boot 代码构造,那么就不须要应用 @ComponentScan 注解的任何参数。所有的组件类文件都被注册为 Spring Beans。

上面的示例阐明如何主动注入 Rest Template 对象并创立一个雷同的:

@Bean

public RestTemplate getRestTemplate() {

return new RestTemplate();

}

以下代码展现如何在主 Spring Boot 利用类文件中主动注入 Rest Template 对象及其 Bean 对象:

package com.tutorialspoint.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