Announcement Announcement Module
No announcement yet.
BeanFactory, FactoryBean and & Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • BeanFactory, FactoryBean and &

    This is section 3.6.1 from the ref manual:
    "3.6.1. Obtaining a FactoryBean, not its product
    Sometimes there is a need to ask a BeanFactory for an actual FactoryBean instance itself, not the bean it
    produces. This may be done by prepending the bean id with & when calling the getBean method of BeanFactory
    (including ApplicationContext). So for a given FactoryBean with an id myBean, invoking getBean("myBean")
    on the BeanFactory will return the product of the FactoryBean, but invoking getBean("&myBean") will return
    the FactoryBean instance itself."

    My question is this: if you want an instance of the factory that gives you "myBean", why not instantiate it directly with
    InputStream is = new FileInputStream("beans.xml");
    XmlBeanFactory factory = new XmlBeanFactory(is);

    In other words, isn't "factory" what you get when you ask for factory.getBean(&"myBean")?

    I'm sure I'm missing something here.

  • #2
    I think you're getting the factory term confused.

    BeanFactory is one thing. FactoryBean is another.

    You get beans from the bean factory. Beans can be of many types. One such bean type is a FactoryBean.

    For example, say you have a target called myDaoTarget. And you want to apply an aspect to the calls made against that target. Then your configuration might include a ProxyFactoryBean with an id of myDAO that has a target of myDaoTarget.

    Taking that a step further, maybe you want to access the bean in your application. Typically, you'd look it up with factory.getBean("myDao"); Keep in mind, the "factory" that I'm referring to there is a BeanFactory but the bean it is looking up is a ProxyFactoryBean.

    The question here is what does your application actually have? What it has is a proxy that wraps calls to the target, not the target itself. However, I don't think* the return itself would be castable to the type of Proxy that it is such as ProxyFactoryBean. Internally, Spring creates the proxy via J2SE dynamic proxies or cglib depending or or possibly another based on your configuration

    * - I'm not guaranteeing the correctness of this point. But, I'm in the ballpark.

    Anyway, if for some reason you wanted the ProxyFactoryBean itself so that you could cast the return to a ProxyFactoryBean and access its methods then you'd need to make the call with factory.getBean("&myDao");

    I don't know if that helps but that is my understanding of it at this point.