spring中 FactoryBean和bean

1.整合spring+hibernate中,让spring接管hibernate的session工厂有一段代码

<bean id="sFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

查看源码:org.springframework.orm.hibernate3.LocalSessionFactoryBean:

public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implements BeanClassLoaderAware

在到AbstractSessionFactoryBean:

public abstract class AbstractSessionFactoryBean
		implements FactoryBean<SessionFactory>, InitializingBean, DisposableBean, PersistenceExceptionTranslator 

发现了实现了一个factoryBean<T>,里面给了个泛型(SeesionFactory).


注:这个bean和其他的bean不一样,spring中有两种bean.
普通bean和bean工厂,即FactoryBean. FactoryBean 返回的不是这个类的实例,其返回的是该工厂Bean的getObject()方法所返回的对象
普通的Bean直接返回指定类(配置中的class属性的值)的一个实例.


一个小例子:

package org.ymm.entity;

import org.springframework.beans.factory.FactoryBean;

/**
 * TestBean 类实现了FactoryBean<T>
 * @author witho_000
 *
 */

public class TestBean implements FactoryBean<Object>{

	public Object getObject() throws Exception {
		// TODO Auto-generated method stub
		return "string类型";
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.sprinsgframework.org/schema/context/spring-context-3.0.xsd">
           
	<!-- 测试factorybean -->
	
	<bean id="factorybean1" class="org.ymm.entity.TestBean" />
		
</beans>

package org.ym.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.ymm.entity.TestBean;

/**
 * Tester测试类
 * @author witho_000
 *
 */

public class Tester {
	
	public static void main(String[] args) {	
		
		ApplicationContext cont=new ClassPathXmlApplicationContext("beans.xml");
		String s= cont.getBean("&factorybean1",String.class);
		System.out.println(s.getClass());
	}
}

显然没有报错,返回的正是String类型。而不是spring配置的TestBean类型;


网上找到的小技巧:
String s= cont.getBean("&factorybean1",String.class);
bean的id前加个&得到的就是TestBean


你可能感兴趣的:(FactoryBean)