之前程序中的SessionFactory都是通过hibernate的方式获取的:
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
因为一些问题想要改成Spring注入的方式,但是我的程序都是使用的注解的方式注入bean,为了保持一致性还是用@Bean来配置SessionFactory
首先配置DataSource
@Bean(destroyMethod="close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(password);
return dataSource;
}
这里按照Spring的文档的说法配置DataSource的时候一定要写DestoryMothod
其次配置SessionFactory
我们用XML配置的时候一般用LocalSessionFactoryBean作为implementation,但是用java代码配置的时候发现LocalSessionFactoryBean并没有实现SessionFactory,原来LocalSessionFactoryBean只是一个FactoryBean,其中有一个SessionFactory类型的成员变量,需要调用LocalSessionFactoryBean的getObject()方法返回SessionFactory。
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource());
String rootPath = getClass().getResource("/").getPath();
File file = new File(rootPath+"/hibernate.cfg.properties");
Properties hbtProperties = new Properties();
try {
hbtProperties.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
factoryBean.setHibernateProperties(hbtProperties);
//mapping resoureces 不需要写出文件的全路径,只需要文件名
factoryBean.setMappingResources(new String[]{"hbm.xml"});
try {
//这个方法是真正生成sessionFactory的
factoryBean.afterPropertiesSet();
} catch (IOException e) {
e.printStackTrace();
}
return factoryBean.getObject();
}