Struts+Spring+Hibernate注解零配置整合
[color=red][b]个人努力,请不要转载,收藏就好[/b][/color] 本工程为Maven工程,可以下载maven-eclipse插件进行项目导入 如果在eclipse中用WTP插件配置Tomcat运行,需要把maven项目转成Eclipse工程 请下载附件,解压后在工程文件夹运行以下maven命令: [code="cmd"] call mvn eclipse:eclipse -Dwtpversion=2.0 [/code] 以下是工程的pom.xml文件,用来管理所有依赖的jar包: [code="xml"] 4.0.0 com.tianlihu.projects S2S3H3_demo 1.0.0 war 3.1.4.RELEASE 3.1 xalan xalan 2.7.1 runtime javax.servlet servlet-api 2.5 provided javax.servlet jsp-api 2.0 provided org.apache.struts struts2-core 2.3.8 org.apache.struts struts2-convention-plugin 2.3.8 org.apache.struts struts2-spring-plugin 2.3.8 org.apache.struts struts2-tiles-plugin 2.3.8 org.apache.tiles tiles-jsp 2.0.4 javax.servlet jstl 1.1.0 org.springframework spring-core ${springframe.version} org.springframework spring-aop ${springframe.version} org.springframework spring-context-support ${springframe.version} org.springframework spring-context ${springframe.version} org.springframework spring-aspects ${springframe.version} org.springframework spring-web ${springframe.version} org.springframework spring-beans ${springframe.version} org.springframework spring-jdbc ${springframe.version} org.springframework spring-asm ${springframe.version} org.springframework spring-tx ${springframe.version} org.springframework spring-webmvc ${springframe.version} org.springframework spring-orm ${springframe.version} org.springframework spring-struts ${springframe.version} org.hibernate hibernate-core 3.6.10.Final org.hibernate hibernate-ehcache 3.6.10.Final aopalliance aopalliance 1.0 org.aspectj aspectjrt 1.6.9 org.aspectj aspectjweaver 1.6.9 cglib cglib 2.2 c3p0 c3p0 0.9.1.2 mysql mysql-connector-java 5.1.23 commons-dbcp commons-dbcp 1.4 commons-lang commons-lang 2.5 commons-io commons-io 2.0 commons-httpclient commons-httpclient 3.1 commons-beanutils commons-beanutils 1.8.3 commons-collections commons-collections 3.2.1 junit junit 4.8.1 test org.springframework spring-test ${springframe.version} test org.unitils unitils-core ${unitils.version} test org.unitils unitils-dbunit ${unitils.version} test org.hibernate hibernate org.unitils unitils-easymock ${unitils.version} test org.unitils unitils-spring ${unitils.version} test org.unitils unitils-mock ${unitils.version} test org.unitils unitils-inject ${unitils.version} test org.dbunit dbunit 2.4.8 test ch.qos.logback logback-classic 0.9.28 org.apache.maven.plugins maven-compiler-plugin 2.3.2 1.6 1.6 1.6 GBK true 128m 512m org.apache.maven.plugins maven-resources-plugin 2.6 GBK [/code] 以下是web.xml,已经配置了Struts和Spring: [code="xml"] struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 * encodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding GBK encodingFilter * contextConfigLocation classpath*:applicationContext.xml org.springframework.web.context.ContextLoaderListener index.jsp [/code] Spring主配置文件applicationContext.xml: [code="xml"] [/code] Struts用默认配置,因此不放置struts.xml Hibernate的Spring配置hibernate.cfg.xml文件如下: [code="xml"] ${hibernate.dialect} ${hibernate.show_sql} ${hibernate.format_sql} ${hibernate.temp.use_jdbc_metadata_defaults} ${hibernate.hbm2ddl.auto} ${hibernate.cache.provider_class} ${hibernate.cache.use_query_cache} ${hibernate.cache.use_second_level_cache} false thread [/code] 以下这句用来指明,数据事务用Spring的声明式事务,即使用@Transactional注解 [code="xml"] [/code] 数据库的属性配置文件hibernate.properties如下: [code="properties"] ## hibernate hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl.auto=create-drop hibernate.temp.use_jdbc_metadata_defaults=false ## hibernate cache hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider hibernate.cache.use_query_cache=false hibernate.cache.use_second_level_cache=true ## C3P0 configuration hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK hibernate.connection.username=root hibernate.connection.password=root hibernate.connection.initialPoolSize=1 hibernate.connection.minPoolSize=1 hibernate.connection.maxPoolSize=3 [/code] logback日志配置文件logback.xml如下: [code="xml"] %d{yyyy-MM-dd HH:mm:ss.SSS} %-4relative [%thread] %-5level %logger{36} - %msg %n logs/ssh.%d{yyyy-MM-dd-HH}.log 10 [/code] 以上是所有的配置文件。 JSP代码不再贴出,请下载附件。 以下是java程序代码 用于接收请求的Struts的Action类:UserAction.java [code="java"] package com.tianlihu.projects.ssh.account.action; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.tianlihu.projects.ssh.account.po.User; import com.tianlihu.projects.ssh.account.service.UserService; @ParentPackage("struts-default") @Namespace("/account") @Component public class UserAction { @Autowired private UserService userService; private List users; private String userId; private String name; private String password; private String age; private String message; @Action(value = "createUser", results = { @Result(name = "success", location = "/WEB-INF/userForm.jsp") }) public String createUser() { message = "创建用户"; return "success"; } @Action(value = "create", results = { @Result(name = "success", type = "redirect", params = { "encode", "true" }, location = "fetchUsers?message=${message}") }) public String create() { User user = getUser(); userService.createUser(user); message = "创建用户'" + userId + "'成功"; return "success"; } @Action(value = "updateUser", results = { @Result(name = "success", location = "/WEB-INF/userForm.jsp") }) public String updateUser() { User user = userService.findByUserId(userId); name = user.getName(); password = user.getPassword(); age = String.valueOf(user.getAge()); message = "修改用户'" + userId + "'"; return "success"; } @Action(value = "update", results = { @Result(name = "success", type = "redirect", params = { "encode", "true" }, location = "fetchUsers?message=${message}") }) public String update() { User user = getUser(); userService.updateUser(user); message = "修改用户'" + userId + "'成功"; return "success"; } @Action(value = "delete", results = { @Result(name = "success", type = "redirect", params = { "encode", "true" }, location = "fetchUsers?message=${message}") }) public String deleteUser() { userService.deleteUser(userId); message = "删除用户'" + userId + "'成功"; return "success"; } @Action(value = "fetchUsers", results = { @Result(name = "success", location = "/WEB-INF/users.jsp") }) public String fetchUsers() { users = userService.findAll(); return "success"; } private User getUser() { User user = new User(); user.setUserId(userId); user.setName(name); user.setPassword(password); user.setAge(Integer.parseInt(age)); return user; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List getUsers() { return users; } public void setUsers(List users) { this.users = users; } } [/code] 处理逻辑的Service:UserService.java 因为Service只是处理增删改查,没有验证数据,所以比较简单,值得注意的是,@Transactional事务注解只能写在Service层,不能写在Action层,不然会出错,估计是对Spring3对Struts2支持的不太好 [code="java"] package com.tianlihu.projects.ssh.account.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.tianlihu.projects.ssh.account.dao.GeneralDao; import com.tianlihu.projects.ssh.account.po.User; @Service public class UserService { @Autowired private GeneralDao generalDao; public User findByUserId(String userId) { return generalDao.findById(User.class, userId); } public List findAll() { return generalDao.findAll(User.class); } @Transactional public void createUser(User user) { generalDao.save(user); } @Transactional public void updateUser(User user) { generalDao.update(user); } @Transactional public void deleteUser(String userId) { generalDao.deleteById(User.class, userId); } @Transactional public void deleteUser(User user) { generalDao.delete(user); } } [/code] Hibernate的PO对象:User.java 不再需要用XML进行表和实体类的映射了 [code="java"] package com.tianlihu.projects.ssh.account.po; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity(name = "AC_USER") public class User implements Serializable { private static final long serialVersionUID = -1376216905288707683L; @Id @Column(name = "USER_ID", length =50, nullable = false) private String userId; @Column(name = "NAME", length = 50, nullable = false) private String name; @Column(name = "PASSWORD", length = 50, nullable = false) private String password; @Column(name = "AGE", length = 20, nullable = false) private int age; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } [/code] 数据存储层通用DAO接口定义:GeneralDao.java [code="java"] package com.tianlihu.projects.ssh.account.dao; import java.io.Serializable; import java.util.List; public interface GeneralDao { public T findById(Class type, Serializable id); public List findAll(Class type); public void save(Object... entities); public void update(Object... entities); public void saveOrUpdate(Object entity); public void delete(Object... entities); public void deleteById(Class type, Serializable id); public void refresh(Object... entities); public void flush(); } [/code] DAO的实现类:GeneralDAOImpl.java [code="java"] package com.tianlihu.projects.ssh.account.dao; import java.io.Serializable; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; @Repository public class GeneralDAOImpl implements GeneralDao { @Autowired private HibernateTemplate hibernateTemplate; @Override public T findById(Class type, Serializable id) { return hibernateTemplate.get(type, id); } @Override public List findAll(Class type) { return hibernateTemplate.loadAll(type); } @Override public void save(Object... entities) { for (Object entity : entities) { hibernateTemplate.save(entity); } } @Override public void saveOrUpdate(Object entity) { hibernateTemplate.saveOrUpdate(entity); } @Override public void update(Object... entities) { for (Object entity : entities) { hibernateTemplate.update(entity); } } @Override public void delete(Object... entities) { for (Object entity : entities) { if (entity != null) { hibernateTemplate.delete(entity); } } } @Override public void deleteById(Class type, Serializable id) { if (id == null) { return; } Object entity = findById(type, id); if (entity == null) { return; } delete(entity); } @Override public void refresh(Object... entities) { for (Object entity : entities) { hibernateTemplate.refresh(entity); } } @Override public void flush() { hibernateTemplate.flush(); } } [/code] 这就是整个搭建框架,是一个内核。在应用时,可以配置freemarker之类的其余框架进来,用于实际开发 纯注解形式的代码有助于代码开发和管理,很代码更整洁,测试代码也可以用注解形式,也方便测试。因为注解形式把配置和代码放在一起,维护比较方便,减少了配置和代码的同步,也减少了代码量,使BUG数降低。个人推荐使用注解形式的配置 注解形式的代码,可以算一程契约形式的编程,只关心我想做什么,不关心怎么做,代码的耦合比较小,模块化比较强。JDK7也在主推模块化,这两个方向是以后的发展趋势
一直对maven了解不多,准备借鉴一下。
:idea: 谢谢 ,学到很多东西
恩,写的不错。我借鉴一下。