读书人

spring对于BeanFactory获得对象

发布时间: 2012-10-28 09:54:44 作者: rapoo

spring对于BeanFactory取得对象
今天在看spring与hibernate的代码,发现了一个地方非常难理解,就是我以前搭建的一个spring+hibernate的代码中在DAO中注入HibernateDaoSupport中注入的是的spring的LocalSessionFactoryBean,而属性确实hibernate的SessionFactory,考虑不通,按照正常的思路应该是要保ClassCaseException的,于是查询了一下spring refreence,发现了一句话的描述:
“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 returnthe FactoryBean instance itself”

这句话表明了事情的原委,如果是factorybean的话,他会取得他的方法的产品,所以诸如的是HibernateDaoSupport的产品,就是getSessionFactory的返回值。一个细小的地方,造成误会。
spring处理此处的地方代码如下,可以解释spring如何进行的数据处理

//仔细察看spring的注释
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
??// If it's a FactoryBean, we use it to create a bean instance, unless the
??// caller actually wants a reference to the factory.
??if (beanInstance instanceof FactoryBean) {
???if (!isFactoryDereference(name)) {
????// Return bean instance from factory.
????FactoryBean factory = (FactoryBean) beanInstance;
????if (logger.isDebugEnabled()) {
?????logger.debug("Bean with name '" + beanName + "' is a factory bean");
????}
????try {
?????beanInstance = factory.getObject();
????}
????catch (Exception ex) {
?????throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
????}
????if (beanInstance == null) {
?????throw new FactoryBeanNotInitializedException(
???????? beanName, "FactoryBean returned null object: " +
???????"probably not fully initialized (maybe due to circular bean reference)");
????}
???}
???else {
? ???// The user wants the factory itself.
????if (logger.isDebugEnabled()) {
?????logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");
????}
???}
??}

?

1 楼 dwangel 2008-02-23 如果该 id所引用的bean是FactoryBean实例,则检查是否使用了&,
如果没有则调用FactoryBean的getObject方法来取得产品。

读书人网 >软件架构设计

热点推荐