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

}
相关推荐
l***21787 分钟前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
内存不泄露20 分钟前
基于 Spring Boot 的医院预约挂号系统(全端协同)设计与实现
java·vue.js·spring boot·python·flask
袁慎建@ThoughtWorks24 分钟前
如何发布自定义 Spring Boot Starter
java·spring boot·后端
czlczl200209251 小时前
Quartz基本原理与工程实践
java·spring boot·后端
u0104058361 小时前
Spring Boot与Spring Cloud的协同:构建健壮的微服务架构
spring boot·spring cloud·架构
利刃大大2 小时前
【RabbitMQ】SpringBoot整合RabbitMQ:工作队列 && 发布/订阅模式 && 路由模式 && 通配符模式
java·spring boot·消息队列·rabbitmq·java-rabbitmq
AIGCExplore2 小时前
Jenkins 自动构建编译 Spring Boot 和 Vue 项目
vue.js·spring boot·jenkins
yangminlei2 小时前
Spring Boot 自动配置原理与自定义 Starter 开发实战
java·数据库·spring boot
悟空码字2 小时前
10分钟搞定!SpringBoot集成腾讯云短信全攻略,从配置到发送一气呵成
java·spring boot·后端
未来龙皇小蓝3 小时前
Spring注入Bean流程及其理解
java·spring boot·后端·spring·代理模式