开发者

Anonymous Spring bean

How is an anonymous Sp开发者_运维问答ring bean useful?


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜