The case for Spring inner beans
When code reviewing or pair programming, I’m always amazed by the following discrepancy. On one hand, 99% of developers conscientiously apply encapsulation and limit accessibility and variable scope to the minimum possible. On the other hand, nobody cares one bit about Spring beans and such beans are always set at top-level, which makes them accessible from every place where you can get a handle on the Spring context.
For example, this a typical Spring beans configuration file:
four are only used by bean
five, they shouldn’t be accessible from anywhere else and should be defined as inner beans.
From this point on, beans
four cannot be accessed in any way outside of bean
five; in effect, they are not visible.
There are a couple of points I’d like to make:
- By using inner beans, those beans are implicitly made anonymous but also scoped
prototype, which doesn’t mean squat since they won’t be reused anywhere else.
- With annotations configuration, this is something that is done under the cover when you set a new instance in the body of the method
- I acknowledge it renders the Spring beans definition file harder to read but with the graphical representation feature brought by Spring IDE, this point is moot
In conclusion, I would like every developer to consider not only technologies, but also concepts. When you understand variable scoping in programming, you should not only apply it to code, but also wherever it is relevant.