Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Spring bean

How is an anonymous Spring bean useful?

like image 517
fastcodejava Avatar asked Oct 25 '10 17:10

fastcodejava


2 Answers

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.

like image 143
mR_fr0g Avatar answered Nov 15 '22 08:11

mR_fr0g


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
like image 25
Eugene Kuleshov Avatar answered Nov 15 '22 07:11

Eugene Kuleshov