@RequiredArgsConstructor和@Authwired

我们在java后端书写接口时,对service层成员变量的注入和使用有以下两种实现方式:
1) @RequiredArgsConstructor

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/users")
    public List<User> getUsers(@RequestParam String query) {
        return userService.searchUsers(query);
    }
}

2) @Autowired

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public List<User> getUsers(@RequestParam String query) {
        return userService.searchUsers(query);
    }
}

看完代码,估计大家能看出个大概,不知道有没有人会觉得当成员变量不为final时,就使用@Authwired;为final时,就用@RequiredArgsConstructor,其实不然,我们看下面的代码:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public List<User> getUsers(@RequestParam String query) {
        return userService.searchUsers(query);
    }
}

当成员变量为 final 时,可以使用 @Autowired 注解来进行注入,但是需要结合构造函数注入的方式来实现。
接下来,我们具体看看这两个注解的区别:

  1. 生成构造函数的方式:
    ● @RequiredArgsConstructor:这是 Lombok 提供的注解,它会在编译时根据类中被声明为 final 或 @NonNull 的字段生成一个构造函数。生成的构造函数用于初始化这些字段,并将它们标记为必需参数。这样,在创建对象时,这些字段必须被传入构造函数中。
    ● @Autowired:这是 Spring 框架提供的注解,它用于自动注入依赖项。通过在构造函数、字段或方法上使用 @Autowired 注解,Spring 框架会自动解析依赖项并进行注入。
  2. 适用范围:
    ● @RequiredArgsConstructor:由于是 Lombok 提供的注解,它可以在任何环境中使用,而不依赖于特定的框架或库。
    ● @Autowired:这是 Spring 框架提供的注解,用于在 Spring 环境中实现依赖注入。它需要依赖于 Spring 框架,并且用于在 Spring 应用程序中自动解析和注入依赖项。
  3. 字段修饰符要求:
    ● @RequiredArgsConstructor:该注解可以与 private final 或 @NonNull 修饰的字段一起使用,生成的构造函数会将这些字段标记为必需参数。
    ● @Autowired:该注解可以与非 final 字段一起使用,并且在运行时自动注入相关的依赖项。
    这下,想必你就能清楚的知道他俩的区别了。其实对于成员变量是否为final,主要根据自己的业务需求,看变量在运行时是否需要变化,当然大部分情况下都是final。如果不是final,那只能用@Authwired注解,如果是final,那肯定是@RequiredArgsConstructor更方便,不然用到的service多了,你的构造函数得写多少个参数。而且,@RequiredArgsConstructor还可以用于实体层。
posted @ 2023-07-13 09:48  摸鱼小天才  阅读(148)  评论(0编辑  收藏  举报