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

}
相关推荐
苹果醋336 分钟前
快速玩转 Mixtral 8x7B MOE大模型!阿里云机器学习 PAI 推出最佳实践
spring boot·nginx·毕业设计·layui·课程设计
程序员大金40 分钟前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql
【D'accumulation】2 小时前
令牌主动失效机制范例(利用redis)注释分析
java·spring boot·redis·后端
2401_854391082 小时前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
wxin_VXbishe2 小时前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
OEC小胖胖3 小时前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web
2401_857617623 小时前
SpringBoot校园资料平台:开发与部署指南
java·spring boot·后端
quokka563 小时前
Springboot 整合 logback 日志框架
java·spring boot·logback
计算机学姐3 小时前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
2401_854391084 小时前
Spring Boot大学生就业招聘系统的开发与部署
java·spring boot·后端