Spring, не может изменить значения службы @RequestScope - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь создать службу журналов для хранения двух переменных, которые я буду использовать в течение срока действия http-запроса. Проблема в том, что я не могу изменить поля. я пробовал сеттеры, методы init и я вижу в отладчике изменение значений, но после выхода из метода поля имеют значение null

, единственная причина в том, что я не изменяю тот же объект, но у меня есть RequestScope ....

@Service
@RequestScope
public class LogService {

    private String id;
    private String type;

    public void init(String id, String type) {
       this.id = id;
       this.type = type;
    }
}


@RestController
@RequestMapping("/")
@AllArgsConstructor
public class Controller {

    private OtherService otherService;
    private LogService logService;

    @PostMapping(value = "create", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@RequestBody BodyObject body) {

       /* in the debugger i can see that the values are set in the object but after getting out of the logService.init the object the variables are null */
        logService.init("service", body.getId());

         /* here both fields are null and also inside other services using the  logService */
         otherService.execute(body);
        .....
    }

1 Ответ

0 голосов
/ 01 мая 2020

Невозможно воспроизвести. Вот полный Минимальный воспроизводимый пример :

@Service
@RequestScope
public class LogService {

    private String id;
    private String type;

    @SuppressWarnings("hiding")
    public void init(String id, String type) {
        this.id = id;
        this.type = type;
    }

    public String getId() {
        return this.id;
    }

    public String getType() {
        return this.type;
    }

    @Override
    public String toString() {
        return "LogService[id=" + this.id + ", type=" + this.type + "]";
    }

}
@Service
public class ScopeService {

    @Autowired
    private LogService logService;

    public void test() {
        System.out.println("ScopeService: " + this.logService);
        System.out.println("  id=" + this.logService.getId() + ", type=" + this.logService.getType());
    }

}
@RestController
public class ScopeController {

    @Autowired
    private ScopeService scopeService;
    @Autowired
    private LogService logService;

    @GetMapping("/dmz/scope")
    public String create(@RequestParam String id, @RequestParam String type) throws InterruptedException {
        this.logService.init(id, type);
        Thread.sleep(10000);
        this.scopeService.test();
        return this.logService.toString();
    }

}

Thread.sleep() предназначен для тестирования параллельной обработки веб-запросов, чтобы убедиться, что LogService действительно в области запроса.

Поэтому я использую следующие 2 URL-адреса, которые отправляются в течение 10 секунд друг с другом:
http://localhost:8080/dmz/scope?id=1&type=TEST1
http://localhost:8080/dmz/scope?id=2&type=TEST2

Они возвращают страницы, на которых: LogService[id=1, type=TEST1]
и: LogService[id=2, type=TEST2]

Мой журнал показывает:

2020-05-01 13:10:29.117 DEBUG 5888 --- [nio-8080-exec-1] o.s.w.f.CommonsRequestLoggingFilter      : Before request [GET /dmz/scope?id=1&type=TEST1]
2020-05-01 13:10:30.312 DEBUG 5888 --- [nio-8080-exec-2] o.s.w.f.CommonsRequestLoggingFilter      : Before request [GET /dmz/scope?id=2&type=TEST2]
ScopeService: LogService[id=1, type=TEST1]
  id=1, type=TEST1
2020-05-01 13:10:39.162  INFO 5888 --- [nio-8080-exec-1] shared.EventLogger                       : EVENT: ServletRequestHandledEvent
2020-05-01 13:10:39.162 DEBUG 5888 --- [nio-8080-exec-1] o.s.w.f.CommonsRequestLoggingFilter      : REQUEST DATA : GET /dmz/scope?id=1&type=TEST1]
ScopeService: LogService[id=2, type=TEST2]
  id=2, type=TEST2
2020-05-01 13:10:40.319  INFO 5888 --- [nio-8080-exec-2] shared.EventLogger                       : EVENT: ServletRequestHandledEvent
2020-05-01 13:10:40.320 DEBUG 5888 --- [nio-8080-exec-2] o.s.w.f.CommonsRequestLoggingFilter      : REQUEST DATA : GET /dmz/scope?id=2&type=TEST2]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...