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:
<bean id="one" class="ch.frankel.blog.spring.One" /> <bean id="two" class="ch.frankel.blog.spring.Two" /> <bean id="three" class="ch.frankel.blog.spring.Three" /> <property name="one" ref="one" /> <property name="two" ref="two" /> </bean> <bean id="four" class="ch.frankel.blog.spring.Four" /> <bean id="five" class="ch.frankel.blog.spring.Five"> <property name="three" ref="three" /> <property name="four" ref="four" /> </bean>
four are only used by bean
five, they shouldn’t be accessible from anywhere else and should be defined as inner beans.
<bean id="five"> <property name="three"> <bean class="ch.frankel.blog.spring.Three"> <property name="one"> <bean class="ch.frankel.blog.spring.One" /> </property> <property name="two"> <bean class="ch.frankel.blog.spring.Two" /> </property> </bean> </property> <property name="four"> <bean class="ch.frankel.blog.spring.Four" /> </property> </bean>
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.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)