Announcement Announcement Module
No announcement yet.
BeanFactory reference in config? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • BeanFactory reference in config?

    Is there a way to pass the beanfactory as a reference into an existing object?

    Let's say I have a class that I want to use as a bean within Spring, but don't have the ability to modify it to implement BeanFactoryAware. Is there a special token I can use during configuration to pass a setter an instance of the bean factory?

    For example:

    <bean id="someBean" class="">
    <property name="object"><ref local="&beanfactory"/></property>

    Where this would call setObject(Object obj) on the class and pass it the bean factory reference?


  • #2
    Not sure if this is what you are looking for but you can implement BeanFactoryAware interface on the bean itself and factory will be set.



    • #3
      if you really, really, really don't have the ability to modify your bean to implement BeanFactoryAware, you can create a bean that implements BeanFactoryAware and then injects the BeanFactory it receive into your bean (lot of indirections!!!)
        <-- MySetterBean implements BeanFactoryAware -->
        <bean name="mySetter" class="MySetterBean">
          <property name="myBean">
            <ref local="myBean" />
        <-- My initial Bean -->
        <bean name="myBean" class="MyBean"/>
        public class MySessterBean implements BeanFactoryAware &#123;
        public void setBeanFactory&#40;BeanFactory beanFactory&#41; throws BeansException &#123;
      hhmm, one last thing, If setBeanFactory is fired before setMyBean (I am not sure of the order), you will need to implement InitializingBean and use afterPropertiesSet to inject the BeanFactory into your bean.


      • #4
        I was lazy and subclassed my object and had the subclass implement BeanFactoryAware and call its superclass to do the appropriate set.

        I was a bit lucky since it was a 3rd-party library, and its possible that the class could have been final (although improbable since hardly anyone does this) and was wondering if there was a special token I didn't know about.

        The "factory injector" solution is clever though, it could just use metadata and reflection to inject the application context/bean factory into any bean regardless of it's setup.