0
votes

How can I inject @RequestBody object(value object) to Spring Service layer?

I want to Inject(Autowired)objects what come from request body values.

HelloController

@Autowired
UserService userService;

(….)

@GetMapping("/hello")
public String hello(
        @RequestBody UserRequestBodyDto userDto,
        HttpServletResponse response){

    return null;
}

UserRequestBodyDto

@Data
public class UserRequestBodyDto{
    private String name;
    private String address;
}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService{

    @AutoWired
    public UserServiceImpl(UserRequestBodyDto userDto){
      (….)
    }

}

In that case, how can I inject UserRequestBodyDto objects into service layer?

Add 'setUserDto' method to UserService is the best way? or If convert dto to entity is the best way to inject objets, how can I manage many of same classes between dto class and entity class?

+a) In my opinion, make a RequestScopedBean is bad way.

ref: Spring: injecting @RequestBody into @Bean

1

1 Answers

0
votes

Why you need to @AutoWired a request object? I seems completely unnecessary while doing operation with a request object cause, it will change on every new request.

So you can do operation with request object in the service layer method.

 public UserServiceImpl(UserRequestBodyDto userDto){
      (….)//do operation with userDto here.
 }

Or, I you really need to @AutoWire the request object then declare UserRequestBodyDto userDto in service layer with @AutoWired annotation. And when the service layer method executes just set the values to this.userDto.

@Service
public class UserServiceImpl implements UserService{
    @AutoWired
    private UserRequestBodyDto userDto;

    @AutoWired
    public UserServiceImpl(UserRequestBodyDto userDto){
      this.userDto = userDto;//Here, setting value of userDto to this.userDto
    }

}