用代码配置Spring IoC容器+整合hibernate
1、创建config类
@Configuration
public class AppConfig {}
@Configuration表示这是spring的配置文件
2、配置数据库连接池
@Bean
public DataSource DataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hib?useUnicode=true&characterEncoding=utf8");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setInitialSize(10);
dataSource.setMaxIdle(50);
return dataSource;
}
3、配置会话工厂
@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setPackagesToScan(new String[] {"com.kygo.entity"});
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.format_sql", "true");
bean.setHibernateProperties(props);
return bean;
}
4、配置事务管理
@Bean
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
5、支持动态代理和声明式事务
@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class AppConfig {}
Spring整合struts2+hibernate
需要jar包
spring-web-4.3.7.RELEASE.jar
创建applicationContext.xml和struts.xml
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.devMode" value="true" />
<constant name="struts.action.extension" value="do" />
<package name="default" extends="struts-default" namespace="/">
<action name="index" class="showGoods">
<result>/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
<constant name="struts.objectFactory" value="spring" />
将action对象交给springIoC容器管理
配置web.xml
<!-- 通过上下文参数指定Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置创建Spring IoC容器的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>