1. Integrate spring + hibernate and let spring take over the hibernate session factory with a piece of code
[Java]
<Bean id = "sFactory" class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean">
View the source code: org. springframework. orm. hibernate3.LocalSessionFactoryBean:
[Java]
Public class LocalSessionFactoryBean extends actsessionfactorybean implements BeanClassLoaderAware
At AbstractSessionFactoryBean:
[Java]
Public abstract class AbstractSessionFactoryBean
Implements FactoryBean <SessionFactory>, InitializingBean, DisposableBean, PersistenceExceptionTranslator
A factoryBean <T> is implemented, and a generic (SeesionFactory) is provided ).
Note: This bean is different from other beans. spring has two types of beans.
The common bean and bean factory, that is, FactoryBean. FactoryBean does not return the instance of this class, but returns the object returned by the getObject () method of the factory Bean.
A common Bean directly returns an instance of the specified class (the value of the class attribute in the configuration.
A small example:
[Java]
Package org. ymm. entity;
Import org. springframework. beans. factory. FactoryBean;
/**
* The TestBean class implements FactoryBean <T>
* @ Author witho_000
*
*/
Public class TestBean implements FactoryBean <Object> {
Public Object getObject () throws Exception {
// TODO Auto-generated method stub
Return "string type ";
}
@ Override
Public Class <?> GetObjectType (){
// TODO Auto-generated method stub
Return null;
}
@ Override
Public boolean isSingleton (){
// TODO Auto-generated method stub
Return false;
}
}
[Java]
<? 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>
<! -- Test factorybean -->
<Bean id = "factorybean1" class = "org. ymm. entity. TestBean"/>
</Beans>
[Java]
Package org. ym. test;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Import org. ymm. entity. TestBean;
/**
* Tester test class
* @ 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 ());
}
}
Obviously, no error is returned, which is of the String type. Instead of the TestBean type configured by spring;
TIPS:
String s = cont. getBean ("& factorybean1", String. class );
Add the bean id and get TestBean.
Author: without0815