We have gradually introduced a little Spring in the system I’m working on, and the results have been good. It’s getting easier to write testable code that can be read and modified efficiently, which is saving our customer money. (My account manager told me to end every paragraph of whatever I say or write in “saving money” or something such.)

However, the silver bullet of Spring does not come without feeding problems. A while back I was making a simple Spring singleton service that stored state that was periodically updated. The problem is that the state did not refresh. In despair, I fell to the despised resort of debug logging. This showed me that the internal state of the service was indeed refreshed, but it did not seem so when calling the service from outside. What?

At some point it occurred to me that maybe my singleton was not really a singleton, and that maybe I was refreshing something else than the object that the rest of the software was looking. And indeed a simple test showed that this was the case.

The Spring ApplicationContext was being refreshed in the bootup process, but unfortunately this was after non-Spring legacy code had acquired a reference to the original “singleton” service. Obviously the context refresh could not do anything to the references from outside the Spring application context, so we ended up with two copies.

Fortunately this one was easy to fix. I also added to the application context a simple bean that will throw an exception if it is initialized twice. This causes context reloads to fail with the exception, which might be a good thing as long as we have non-Spring code that will hold on to stale instances of Spring beans on refresh.