tags:

views:

64

answers:

3

How is an anonymous Spring bean useful?

+3  A: 

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);
          }
    }

    <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.

mR_fr0g
+4  A: 

There is several uses:

  • a bean injected inline as dependency in other bean
  • a bean that implements InitializingBean and DisposableBean, so his methods are called by IoC container
  • a bean implementing BeanClassLoaderAware, BeanFactoryPostProcessor and other call-back interfaces
Eugene Kuleshov
+3  A: 

On top of already provided answers (inner bean, life-managing interfaces, configurer of static properties) I would another one, which we use a lot. That is...

  • in combination with autowiring (by type). When you configure multiple objects of given type and you don't really care how they are called in XML.
Grzegorz Oledzki