Anonymous Spring bean

java, javabeans, spring

Solution

There are two uses that i can think of straight of.

As an inner bean

<bean id="outer" class="foo.bar.A">
  <property name="myProperty">
    <bean class="foo.bar.B"/>
  </property>
</bean>

As a configurer of static properties

public class ServiceUtils {

      private static Service service;

      private ServiceUtils() {}
      ...

      public static void setService(Service service) {
        this.service = service;
      }
    }

    public class ServiceConfigurer {
      private static Service service;

      private ServiceUtils() {}
      ...

      public void setService(Service service) {
        ServiceUtils.setService(service);
          }
    }

Now that class can be configured like this.

<bean class="foo.bar.ServiceConfigurer">
    <property name="service" ref="myService"/>
</bean>

In addition if there is a bean that is not depended upon by any other bean eg RmiServiceExporter or MessageListenerContainer then there is no need other than code clarity to give this bean a name.

Problem

How is an anonymous Spring bean useful?

Original source

Related problems