java – Spring:将@RequestBody注入@Bean

我想在我的控制器更新(…)执行/执行之前填充requestScopedBean.userDetails.

在我的春季网络项目中,我有基于Java的MyConfiguration扩展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的依赖注入或一些基于工厂方法的注入,但请告知其他方法是否更合适.谢谢

最佳答案 如果您只想保留来自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对象中使用Autowire

public class RequestScopedBean {

    public UserDetails userDetails;

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

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

请告诉我,您使用此方法遇到的问题是什么.

点赞