配置数据源
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/数据库?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="3"/>
<property name="maxActive" value="500"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
</bean>
配置sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>cn/xx/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
</value>
</property>
</bean>
在struts-config文件中, 配置这个之后,Struts就会被Spring接管
<!-- 配置代理请求处理 DelegatingRequestProcessor -->
<controller>
<set-property value="org.springframework.web.struts.DelegatingRequestProcessor" property="processorClass"/>
</controller>
然后接着在Spring容器中配置Action
<!-- 配置action -->
<bean class="com.haitao.web.action.UserAction" name="/user" scope="prototype">
<property name="" ref=""/>
</bean>
在web.xml文件中加入如下Filter,解决中文乱码问题
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
加入下面的Filter,解决懒加载问题
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring容器中启动事务管理器,如果某个Bean需要用到事务,只需要在bean类前加 @Transactional ,加上之后,该类中用到的所有的事务都被Spring的事务管理器接管了
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
加上 下面的注解方式,同时在bean类的属性前面加上@Resource,就会启用byName方式为这个属性自动装配
<!-- 启用注解方式 -->
<context:annotation-config/>
配置Service
<!-- 配置Service -->
<bean class="com.haitao.services.imp.UserService" id="userService">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
Web容器初始化Spring容器,需要在web.xml文件中添加如下配置
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
FR:海涛高软(hunk Xu)