springboot教程-@Autowired详解

概述

本文介绍,使用 @Autowired 注解实现依赖注入

源码

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}

使用

可声明的部分较多,但一般用于声明成员变量

作用

默认根据 类型 注入:

  • 当spring容器中,只有一个 bean对象类型,与要注入的 变量类型 匹配,就自动注入

  • 如果 没有匹配 的 会报错

  • 如果 有多个匹配 的 会报错

required 属性

在 spring容器中,是否必须有此类型的对象。默认为true,表示必须有,否则报错

例子

修改Controller,由于 StudentCtrl 需要调用 StudentSrvImpl,那么在 StudentCtrl 类中声明 StudentSrvImpl 类型的成员变量,并在上面使用 @Autowired 注解

@RestController
public class StudentCtrl {

    @Autowired
    private IStudentService studentService;

    @RequestMapping("/student/query")
    public JsonResult query(){
        studentService.query();
        return new JsonResult(0,"查询成功!");
    }
}

说明

当spring容器中,如果只有一个 bean对象类型,与要注入的 变量类型 匹配,就自动注入


原文出处:/show_1IXiydJmZMh.html