@Override public Object get(String name, ObjectFactory<?> objectFactory) { try { Object mutex = RequestContextHolder.currentRequestAttributes().getSessionMutex(); synchronized (mutex) { return super.get(name, objectFactory); } } catch (IllegalStateException e) { logger.debug("outside web session"); ThreadLocal<Object> objectHolder = objectHolders.get(name); if (objectHolder == null) { objectHolders.put(name, new NamedThreadLocal<>("wideScopeObjectHolder_" + name)); objectHolder = objectHolders.get(name); } if (objectHolder.get() == null) { objectHolder.set(objectFactory.getObject()); } return objectHolder.get(); } }
@Test public void test(){ final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<Object>("Prototype beans currently in creation"); Assert.assertNull(prototypesCurrentlyInCreation.get()); prototypesCurrentlyInCreation.set("abc"); Assert.assertNotNull(prototypesCurrentlyInCreation.get()); prototypesCurrentlyInCreation.set(new HashSet<String>()); Assert.assertNotNull(prototypesCurrentlyInCreation.get()); prototypesCurrentlyInCreation.remove(); Assert.assertNull(prototypesCurrentlyInCreation.get()); System.out.println(prototypesCurrentlyInCreation.toString()); }