gpt4 book ai didi

java - Spring:将@RequestBody 注入(inject)@Bean

转载 作者:搜寻专家 更新时间:2023-11-01 03:33:13 25 4
gpt4 key购买 nike

我想在 Controller 的 update(...) 执行时/执行之前填充 requestScopedBean.userDetails

在我的 spring web 项目中,我有基于 java 的MyConfiguration extends WebMvcConfigurerAdapter,其中我有:

@Bean(name = "requestScopedBean")
@Scope(value = "prototype")
public RequestScopedBean requestScopedBean() {
return new RequestScopedBean();
}

RequestScopedBean.java 中:

public class RequestScopedBean {

public @Autowired UserDetails userDetails;

public void setUserDetails(UserDetails pUserDetails){
userDetails = pUserDetails;
}

@Override
public String toString() {
return "" + (userDetails != null) ;
}
}

UserDetails.java

public class UserDetails {
private Long id;
private String name;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

我有 UsersController.java 包含:

@RestController
@RequestMapping("/users")
@Scope("request")
public class UsersController {

@Autowired
private RequestScopedBean requestScopedBean;

@RequestMapping(
value = {"{uid}" },
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public ResponseEntity<?> update(
@PathVariable String uid,
@RequestBody UserDetails pUserDetails
) throws Exception {

// LOCATION 1

// return ResponseEntity;
}
}

我该怎么做才能在 LOCATION 1 处,requestScopedBean.userDetails 保存在此函数中作为参数接收的变量 pUserDetails

我正在寻找一些基于setter 的依赖注入(inject)一些基于工厂方法的注入(inject),但如果其他方法更合适,请告知。谢谢

最佳答案

如果您只想保留来自 Request 的 UserDetails 对象,只需将该对象设置为 requestScopedBean。

@RestController
@RequestMapping("/users")
@Scope("request")
public class UsersController {

@Autowired
private RequestScopedBean requestScopedBean;

@RequestMapping(
value = {"{uid}" },
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public ResponseEntity<?> update(
@PathVariable String uid,
@RequestBody UserDetails pUserDetails
) throws Exception {

requestScopedBean.setUserDetails(pUserDetails);

// return ResponseEntity;
}
}

除此之外,我建议您不要在 RequestScopedBean 的 UserDetails 对象中 Autowiring

public class RequestScopedBean {

public UserDetails userDetails;

public void setUserDetails(UserDetails pUserDetails){
userDetails = pUserDetails;
}

@Override
public String toString() {
return "" + (userDetails != null) ;
}
}

请告诉我,您在使用这种方法时遇到的问题是什么。

关于java - Spring:将@RequestBody 注入(inject)@Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41737966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com