如何将@RequiredArgsConstructor和@Autowired合并为一个?

摘要:我们在java后端书写接口时,对service层成员变量的注入和使用有以下两种实现方式: **1) @RequiredArgsConstructor** ``` import lombok.RequiredArgsConstructor;
我们在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 注解来进行注入,但是需要结合构造函数注入的方式来实现。 接下来,我们具体看看这两个注解的区别: 生成构造函数的方式: ● @RequiredArgsConstructor:这是 Lombok 提供的注解,它会在编译时根据类中被声明为 final 或 @NonNull 的字段生成一个构造函数。生成的构造函数用于初始化这些字段,并将它们标记为必需参数。
阅读全文