Where Are The Wise Men?

Mike's Ramblings

Digging Yourself Into the Circular Injection Hole

| Comments

Late last week I had to do some major refactoring. One of the things I needed to add was some Spring injection from SomeClass1 into SomeClass2. No big deal -- I do this all the time. But after I did that, Spring would error out, saying that there was a [circular injection.][]

This circular injection was not something we did on purpose, but instead was something that evolved. We have functionality in SomeClass1 that we needed in SomeClass3, so we just injected that whole object into SomeClass3. The problem was that SomeClass3 was injected into SomeClass2. Then, when I tried my injection above, Spring rightfully said, "Uh, sorry, I can't do that." So I ended up spending a few days taking two large bits of functionality out of SomeClass1 and put them each into separate classes to be injected everywhere we needed them to be. Their injection was kept to a minimum, of course. Then inject these classes into the places that needed them, and run all the unit tests to make sure everything is still okay. Only after all that could we continue.

Why didn't we do this in the first place? Because we took the fast and easy way of just injecting our classes every-which-way and then getting bit when we least expected it. I mean, the SomeClass1 was really called "XXHandler"!! Injecting a handler class should have told us we were wrong!

So, never again. I want small, simple classes that I can inject into other classes without fear.