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

}
相关推荐
惊鸿Randy1 天前
Spring Boot 应用 Docker 部署完整指南
spring boot·docker
ArabySide1 天前
【Spring Boot】用Spring AOP优雅实现横切逻辑复用
java·spring boot·后端
南山乐只1 天前
Spring Boot 2.x => 3.x 升级指南
java·spring boot·后端
Q_Q19632884751 天前
python+django/flask+vue的智能房价分析与预测系统
spring boot·python·django·flask·node.js·php
汝生淮南吾在北1 天前
SpringBoot3+Vue3新闻动态网站
前端·javascript·vue.js·spring boot·毕业设计·毕设
Q_Q5110082851 天前
python+django/flask+vue的购物管理系统
spring boot·python·django·flask·node.js
Q_Q5110082851 天前
python+springboot+django/flask基于数据挖掘的高考志愿推荐系统
spring boot·python·django·flask·node.js·php
Q_Q5110082851 天前
python+springboot+django/flask基于用户评论主题挖掘的旅游景点推荐系统
spring boot·python·django·flask·node.js
JavaBoy_XJ1 天前
Mysql在 Spring Boot 项目中的完整配置指南
数据库·spring boot·mysql·mysql配置
paopaokaka_luck1 天前
基于SpringBoot+Vue的高校心理健康服务平台(websocket实时聊天、AI分析、Echarts图形化分析)
vue.js·spring boot·websocket·mysql·echarts