我们在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 注解来进行注入,但是需要结合构造函数注入的方式来实现。
接下来,我们具体看看这两个注解的区别: