@Autowired注解推荐使用方法:用在构造方法上

说明

@Autowired注解,用于自动将一个对象注入到当前的对象中。

spring 推荐使用构造器注入的方式。

spring 不推荐@Autowired注解用于字段

构造器注入

依赖注入,通过@Autowired注解,用在构造方法上。

如果只有一个构造方法,则@Autowired注解可以省略

示例

代码

java 复制代码
package com.example.web.controller;

import com.example.web.entity.User;
import com.example.web.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {

    private final UserService userService;


    public UserController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping
    public List<User> selectAll() {
        return userService.list();
    }

}

经过测试,如上的代码中,userMapper 对象,可以被正确注入到Controller对象中。

单元测试,必须添加@Autowired注解

在单元测试时,通过构造器依赖注入,未添加@Autowired注解,运行单元测试方法时会报错。

单元测试时,构造器上必须添加@Autowired注解。

报错信息

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter com.example.web.service.UserService userService in constructor com.example.ServiceTest(com.example.web.service.UserService).

正确代码(添加了@Autowired)

java 复制代码
package com.example;

import com.example.web.entity.User;
import com.example.web.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class ServiceTest {

    private final UserService userService;


    @Autowired
    ServiceTest(UserService userService) {
        this.userService = userService;
    }


    @Test
    void list() {
        List<User> list = userService.list();
        System.out.println(list);
    }

}
相关推荐
鱟鲥鳚7 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
腾渊信息科技公司9 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
隔窗听雨眠13 小时前
Spring Boot在云原生时代的编程范式革新研究
spring boot·后端·云原生
其美杰布-富贵-李15 小时前
Spring Boot 工程开发全流程说明
java·spring boot·后端
dear_bi_MyOnly17 小时前
【SpringBoot配置文件】
java·spring boot·后端·学习·spring·java-ee·学习方法
其美杰布-富贵-李18 小时前
Spring Boot 依赖注入说明文档
java·spring boot·python
流烟默18 小时前
SpringBoot应用链路追踪 traceId 技术方案
spring boot·skywalking·traceid
耀耀_很无聊20 小时前
13_Spring Boot 3.5.8 + Redisson 3.45.1 导致 Sa-Token 登录 StackOverflowError
spring boot·后端·bootstrap
霸道流氓气质20 小时前
SpringBoot中集成阿里云消息队列 ApsaraMQ for RabbitMQ 全面指南
spring boot·阿里云·java-rabbitmq
霸道流氓气质20 小时前
SpringBoot中实现告警判定算法-位报警与模拟量阈值-技术详解
spring boot·算法·jquery