Over a million developers have joined DZone.
Platinum Partner

The Case for Spring Inner Beans

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

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 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" />

If beans one, two, three and 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 name="two">
                <bean class="ch.frankel.blog.spring.Two" />
     <property name="four">
         <bean class="ch.frankel.blog.spring.Four" />

From this point on, beans one, two, three and 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:

  1. 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.
  2. With annotations configuration, this is something that is done under the cover when you set a new instance in the body of the method
  3. 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.

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


Published at DZone with permission of Nicolas Frankel , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}