Spring: ‘request’ scoped beans into the background thread

It is known that there no way to deal with request-scoped beans outside of request thread. But sometimes it is required to check such beans for existence, because the algorithm should works whether is it a request context or not. The wondering thing is that such bean is not null even in background thread. So we need something more than bean != null.

The working way to do that is:

@Autowired(required = false)
private RequestScopedBean requestScopedBean;

private RequestScopedBean getRequestScopedBean() {
    if (AopUtils.isAopProxy(requestScopedBean) && 
        requestScopedBean instanceof Advised) {
        try {
            Advised advised = (Advised) this.requestScopedBean;
            TargetSource targetSource = context.getTargetSource();
            Object target = targetSource.getTarget();
            return (RequestScopedBean)target;
        } catch (Exception e) {
            // do nothing
        }
    }
    return null;
}

Looking for conventional approach…

Spring: ‘request’ scoped beans into the background thread

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Можно использовать следующие HTML-теги и атрибуты: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>