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

}
相关推荐
步行cgn4 分钟前
@RestController 详解:从源码到实践
spring boot
边境悍匪1 小时前
springboot常用注解
java·spring boot·学习
李昊哲小课1 小时前
Spring Boot 4 旅游主题实战教程 阶段四:缓存与底层进阶
spring boot·redis·缓存·性能优化·log4j·旅游·性能
QQ_21696290963 小时前
【源码编号:project93375】SpringBoot汽车维修管理信息系统:客户车辆、维修预约、工单派发、配件结算全流程实战
java·spring boot·后端·汽车·springboot·需求分析
xcl09253 小时前
流浪宠物领养管理系统开发实战:从需求分析到落地的完整指南
java·spring boot·需求分析·宠物
2601_962063234 小时前
【Spring Boot】掌握 Spring 事务:隔离级别与传播机制解读与应用
spring boot·spring·adb
gis开发之家4 小时前
Spring Boot 4 深度解析,JdbcTemplate 实战——轻量级数据库操作方案
java·数据库·spring boot·后端
李昊哲小课5 小时前
Spring Boot 4 旅游主题实战教程 阶段二:Web 开发基础
前端·spring boot·旅游
2601_962063975 小时前
Spring Boot拦截器(Interceptor)详解
java·spring boot·后端
李昊哲小课6 小时前
SpringBoot4 云端咖啡站 阶段一:起步与基础
spring boot