Spring 2.5.6 + Struts 2.1.6 + Hibernate 3.3.1 GA + Jboss 4.2.2 整合
时间:2010-10-18 来源:tea_pig
从网上东拼西凑的文章中,然后一个一个包的测试,首先我先在Tomcat下测试的。所以其中多了几个tomcat需要的commons包。
首先贴一下Web.xml文件的内容吧。
2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6
7 <session-config>
8 <session-timeout>30</session-timeout>
9 </session-config>
10
11 <!-- log4j配置文件 -->
12 <context-param>
13 <param-name>log4jConfigLocation</param-name>
14 <param-value>/WEB-INF/classes/log4j.properties</param-value>
15 </context-param>
16
17 <!-- Spring配置文件位置 -->
18 <context-param>
19 <param-name>contextConfigLocation</param-name>
20 <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
21 </context-param>
22
23 <!-- 加载Spring配置文件 -->
24 <listener>
25 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
26 </listener>
27
28 <!--解决Hibernate延迟加载出现的问题,需要放到struts2过滤器之前-->
29 <filter>
30 <filter-name>lazyLoadingFilter</filter-name>
31 <filter-class>
32 org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
33 </filter>
34
35 <!-- Struts过滤器 -->
36 <filter>
37 <filter-name>struts2</filter-name>
38 <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
39 </filter>
40
41 <!--解决Hibernate延迟加载出现的问题,仍需要放到struts2过滤器mapping之前-->
42 <filter-mapping>
43 <filter-name>lazyLoadingFilter</filter-name>
44 <url-pattern>*.action</url-pattern>
45 </filter-mapping>
46
47 <filter-mapping>
48 <filter-name>struts2</filter-name>
49 <url-pattern>/*</url-pattern>
50 <dispatcher>REQUEST</dispatcher>
51 <dispatcher>FORWARD</dispatcher>
52 </filter-mapping>
53
54 <filter>
55 <filter-name>EncodeFilter</filter-name>
56 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
57 <init-param>
58 <param-name>encoding</param-name>
59 <param-value>UTF-8</param-value>
60 </init-param>
61 </filter>
62 <filter-mapping>
63 <filter-name>EncodeFilter</filter-name>
64 <url-pattern>/*</url-pattern>
65 </filter-mapping>
66
67 <welcome-file-list>
68 <welcome-file>index.jsp</welcome-file>
69 </welcome-file-list>
70 </web-app>
71
然后再贴一下applicationContext.xml文件的内容。毕竟是spring配置,最核心的东西,把所有其他框架整合到一起的枢纽。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<description>Spring公共配置文件</description>
<!-- 启用注解 -->
<context:annotation-config />
<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<context:component-scan base-package="com.gts.cns" />
<!-- 定义数据源的Bean ,提供给Hibernate的sessionFactory-->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/MySqlDS" />
</bean>
<!-- 定义数据源的Bean ,提供给Hibernate的sessionFactory-->
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">-->
<!-- <property name="driverClassName" value="com.mysql.jdbc.Driver">-->
<!-- </property>-->
<!-- <property name="url" value="jdbc:mysql://localhost:3306/TPig">-->
<!-- </property>-->
<!-- <property name="username" value="root"></property>-->
<!-- <property name="password" value="admin"></property>-->
<!-- </bean>-->
<!-- 定义Hibernate的sessionFactory,通过该Bean,可以获得Hibernate的Session-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- 自动扫描Class的hibernate映射文件 -->
<property name="packagesToScan">
<list>
<!--若写成model.* 则映射不到,还没有来得及看源代码 -->
<value>*</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<!-- 使用配置文件方式 -->
<!-- <property name="mappingResources">-->
<!-- <list>-->
<!-- <value>model/TbUser.hbm.xml</value>-->
<!-- </list>-->
<!-- </property>-->
</bean>
<!--======================== 事务配置 ========================-->
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!-- 配置事务特性 ,配置add、delete和update开始的方法,事务传播特性为required-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!--
配置那些类的方法进行事务管理,当前com.gts.cns.*.service包中的子包、类中所有方法需要,还需要参考tx:advice的设置
-->
<aop:config>
<aop:pointcut id="allManagerMethod"
expression="execution (* com.gts.cns.*.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" />
</aop:config>
</beans>
在里面也包含了另一个使用Tomcat的DataSource,已经注释起来了。我后面使用的Jboss,所以就先注释起来了。
最后一个配置文件就是struts.xml的内容了
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.action.extension" value="shtml" />
<constant name="struts.objectFactory" value="spring" />
<include file="struts-default.xml" />
<package name="default" extends="struts-default">
<interceptors>
<interceptor-stack name="defaultStack"></interceptor-stack>
</interceptors>
<global-results>
<result name="error">/error.jsp</result>
</global-results>
</package>
<include file="struts-login.xml" />
</struts>
为了业务区分,我把struts文件放不同文件中
struts-login.xml 的内容
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="user" extends="default">
<!--登录界面 -->
<action name="login" class="com.gts.cns.login.action.UserLoginAction"
method="login">
<result name="success">
/jsp/login.jsp
</result>
</action>
<action name="loginError" class="com.gts.cns.login.action.UserLoginAction"
method="error">
<result name="success">
/jsp/error.jsp
</result>
</action>
</package>
</struts>
接着我这里贴一下我的测试代码
Action部分
* Create by TPig
* Since 2010上午09:43:36
*/
package com.gts.cns.login.action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.gts.cns.base.BaseAction;
import com.gts.cns.login.service.IUserLoginService;
/**
* 类说明:
* Create by TPig
* Since 2010上午09:43:36
*/
@SuppressWarnings("serial")
public class UserLoginAction extends BaseAction {
/**
* 用户登录测试接口
*/
@Autowired
@Qualifier("userLoginService")
private IUserLoginService userLoginService;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public String login() {
this.userLoginService.userTest();
this.name = "test";
return SUCCESS;
}
public String error() {
return SUCCESS;
}
private String name;
}
Service部分
* Create by TPig
* Since 2010上午09:47:35
*/
package com.gts.cns.login.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gts.cns.base.impl.BaseServiceImpl;
import com.gts.cns.login.dao.IUserLoginDao;
import com.gts.cns.login.service.IUserLoginService;
/**
* 类说明:
* Create by TPig
* Since 2010上午09:47:35
*/
@Service("userLoginService")
public class UserLoginServiceImpl extends BaseServiceImpl implements IUserLoginService {
@Autowired
private IUserLoginDao userLoginDao;
/*
* (non-Javadoc)
* @see com.gts.cns.userlogin.service.IUserLoginService#userTest()
*/
public String userTest() {
System.out.println("==============进入Service==================");
this.userLoginDao.daoTest();
return "test";
}
}
Dao部分
* Create by TPig
* Since 2010上午10:31:15
*/
package com.gts.cns.login.dao.impl;
import java.util.List;
import model.TbUser;
import org.springframework.stereotype.Repository;
import com.gts.cns.base.impl.BaseDaoImpl;
import com.gts.cns.login.dao.IUserLoginDao;
/**
* 类说明:
* Create by TPig
* Since 2010上午10:31:15
*/
@Repository("userLoginDao")
public class UserLoginDaoImpl extends BaseDaoImpl implements IUserLoginDao {
/*
* (non-Javadoc)
* @see com.gts.cns.userlogin.dao.IUserLoginDao#daoTest()
*/
@SuppressWarnings("unchecked")
public void daoTest() {
System.out.println("=================进入DAO==================");
String hql = "from TbUser";
List<TbUser> userList = this.getHibernateTemplate().find(hql);
for (TbUser tbUser : userList) {
System.out.println(tbUser.getText());
}
}
}
Bean部分
* Create by TPig
* Since 2010下午10:39:05
*/
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 类说明:
* Create by TPig
* Since 2010下午10:39:05
*/
@Entity
@Table(name="tb_user")
public class TbUser {
@Id
@GeneratedValue
@Column(name="id")
private int id;
@Column(name="user")
private String user;
@Column(name="text")
private String text;
/**
* 构造函数
*/
public TbUser() {
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the user
*/
public String getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(String user) {
this.user = user;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
}
数据库部分我就贴一下图片吧
这个是数据库内容了
现在我把jboss启动起来,因为我使用MyEclipse的插件,所以JBoss的配置文件不需要更改
直接启动起来后发现问题了。
Caused by: java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
at org.springframework.orm.hibernate3.support.HibernateDaoSupport.checkDaoConfig(HibernateDaoSupport.java:117)
at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
... 150 more
其中主要看这条错误,告知是sessionFactory或者hibernateTemplate是空的,其实原本我也不知道是怎么一回事,直接就google了,发现已经有人跟到hibernate源码里面去了,并且提示sessionFactory为空的。我也就参照那位仁兄的建议,手动塞进去了。
代码如下:
@Resource(name="sessionFactory")public void setSuperSessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
这块代码我就写在了BaseDaoImpl.java中,因为我每一层之上都加了一个base层,我是考虑为今后加统一功能的时候方便,现在就正好派上用场了。然后我再次启动服务器。
问题又来了
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: java.lang.NoSuchMethodException: org.hibernate.validator.ClassValidator.<init>(java.lang.Class, java.util.ResourceBundle, org.hibernate.validator.MessageInterpolator, java.util.Map, org.hibernate.annotations.common.reflection.ReflectionManager)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:192)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectMethods(InjectionMetadata.java:117)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:302)
... 151 more
这个问题就比较折腾了,我当时也无从着手的感觉,网上搜索的也乱七八糟的,有点似是而非的感觉。偶然看到一帖中说到,jboss的hibernate老了,只要删除就可以了。为了以防万一,我将jboss中的hibernate-*.jar全部贴到文件夹外面。然后重启就正常了。后面我一个包一个包的测试,证实了之前帖子中说的,hibernate-annotations.jar这个包的问题。只要将这个包删除就可以了。jboss4.2.2服务器就完全正常了。因为后续功能还没加上去,所以是否还缺少包我就不得而知了,只能一步一步来。希望我遇到的问题的解决方案,能够帮到各位吧。如果有错误,也请提出来。谢谢。