Java 变量被覆盖
我已经用Spring Boot和Lombok编写了一些代码。我有两个对象,Java 变量被覆盖,java,spring-boot,dependency-injection,lombok,Java,Spring Boot,Dependency Injection,Lombok,我已经用Spring Boot和Lombok编写了一些代码。我有两个对象,user和loggedInUser都基于user.class。我为每个对象userEmail字段指定了不同的值。我得到了以下代码。user是来自端点的请求中的内容,而loggedInUser是执行请求的用户 这是用户类: @Component @Data public class User { private String userEmail; } 这是我使用的User.class private Use
user
和loggedInUser
都基于user.class
。我为每个对象userEmail
字段指定了不同的值。我得到了以下代码。user
是来自端点的请求中的内容,而loggedInUser
是执行请求的用户
这是用户类
:
@Component
@Data
public class User {
private String userEmail;
}
这是我使用的User.class
private User user;
private User loggedInUser;
private SearchParameters searchParameters;
public UserController(
User user,
User loggedInUser,
SearchParameters searchParameters, {
this.user = user;
this.loggedInUser = loggedInUser;
this.searchParameters = searchParameters;
}
@GetMapping(value = "${apiVersion.v_1}" + "/users")
public ResponseEntity getUsers(
@RequestParam("userEmail") String userEmail,
@RequestParam("direction") String direction,
@RequestParam("limit") String limit) {
Jws<Claims> jwsClaims = (Jws<Claims>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
loggedInUser.setUserEmail(jwsClaims.getBody().getSubject()); //From a JWT the logged in user's e-mail is picked up. In this case joe@example.com
log.info("loggedInUser.getUserEmail #1: " + loggedInUser.getUserEmail());
user.setUserEmail(userEmail); // From the request parameters the email is that will be used for the search is picked up. In this case smith@example.com
searchParameters.setDirection(direction); //Can be "u" or "d" that corresponds to "SELECT * FROM user_tbl WHERE < user.getEmail()" or "SELECT * FROM user_tbl WHERE > user.getEmail()" in the SQL that will run in another class
searchParameters.setLimit(limit); //An integer that will limit the number of returned results from the user_tbl
log.info("loggedInUser.getUserEmail #2: " + loggedInUser.getUserEmail());
//The search is done in another class that is taking user.getEmail() as an argument and returns a List of users
我本以为
user
和loggedInUser
是两个独立的对象,因为它们有不同的名称,依赖项注入每次都实例化一个新对象,但看起来user
正在覆盖loggedInUser
。我在这里遗漏了什么?是否可能user
和loggedInUser
实际上是同一个对象?您可以使用调试器来检查这一点。并且依赖项注入每次都实例化一个新对象:您认为为什么会这样?默认情况下,SpringBean是单例的。@jbnize抱歉,我可能把它弄混了。这是否意味着user
和loggedInUser
是同一个对象?是的。这就是它的意思。我认为你的整个设计毫无意义,你应该阅读关于Spring的文章来理解你在做什么。loggedInUser
应该代表什么?我可以理解这是一个具有请求或会话范围的Springbean。但绝对不是单身汉。但是user
应该代表什么呢?为什么是春豆?
loggedInUser.getUserEmail #1: joe@example.com
loggedInUser.getUserEmail #2: smith@example.com