@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);
    }

}
相关推荐
一條狗26 分钟前
学习日报 20260423|[特殊字符] 深度解析:Vue 3 SPA 部署到 Spring Boot 的 404/500 错误排查与完美解决方案-2
vue.js·spring boot·学习
青槿吖29 分钟前
第二篇:从复制粘贴到自定义规则!Spring Cloud Gateway 断言 + 过滤全玩法,拿捏微服务流量管控
java·spring boot·后端·spring cloud·微服务·云原生·架构
wljt1 小时前
SpringBoot学习笔记五:Spring Boot的web开发
spring boot·笔记·学习
anzhxu1 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
lUie INGA2 小时前
快速在本地运行SpringBoot项目的流程介绍
java·spring boot·后端
JAVA学习通3 小时前
AI Agent 工具调用机制与 Spring Boot 工程集成(2026 实战指南)
人工智能·spring boot·后端
一條狗3 小时前
学习日报 20260423|Vue SPA 部署到 Spring Boot:404/500 错误排查与解决方案1
vue.js·spring boot·学习
召田最帅boy3 小时前
一次OOM排查实录
linux·jvm·spring boot·adb
彭于晏Yan3 小时前
Spring Boot + WebSocket 实现单聊已读未读(四)
spring boot·python·websocket
彭于晏Yan4 小时前
Spring Boot 整合 WebSocket + Redis 实现离线消息(三)
spring boot·redis·websocket