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…