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