Struts2、Spring2.5和Hibernate3.2是现在最常用的轻量级JavaEE配套解决方案。几个月的使用后我感觉到Spring传统的xml配置方式配置文件庞大,跟踪很费力。Spring2.5提供了基于annotation的配置。使用annotation配置后,不需要每个bean都写到xml中,只需要在类声明前加一个@Component或者@Service就好了,事务控制更是简单,一个@Transactional就好。配置清爽了,后来的小家伙们也容易读了。
Hibernate方面使用xml配置时经常会遇到实体类添加了新属性,而配置文件没有同步修改带来的问题。改用annotation配置一方面解决了容易遗漏对配置文件的修改的问题,同时也减少了配置文件的体积。参考了reference和若干网文后,我总结了如下简洁的配置策略。
spring的配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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">
<context:annotation-config />
<context:component-scan base-package="quickstart" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="classpath:/hibernate.cfg.xml" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
这里我采用了Hibernate配置文件独立存放的策略,对这两份不相关领域的文件单独维护。Hibernate配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:/comp/env/jdbc/QuickstartDB</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<mapping class="quickstart.model.Person"/>
</session-factory>
</hibernate-configuration>
这里采用了服务器通过JNDI提供的数据源,而不是很多人喜欢的Spring提供数据源,后面再做解释。另外,这里需要将实体类一一列出,Hibernate annotation不支持自动搜索标注实体类,试过,<mapping package="..."/>不是干这个用的。
下面对方案选择进行一下解释:
-
使用Hibernate annotation而不是JPA(Hibernate EntityManager),是因为JPA的API还没有Hibernate的好用,在处理分页的时候Criteria比Query简洁多了。关于分页,另起帖子说。
-
使用服务器通过JNDI提供的数据源而非Spring数据源,是因为服务器上配置数据源很灵活,如果使用Spring的数据源,就相当于把数据库的地址写死在程序里了。应用部署到客户那里,他们一旦有类似修改服务器IP地址的操作,就需要修改数据源的配置。这时如果配置在spring的xml文件中就麻烦了。而目前常用的servlet服务器都提供可视化的数据源配置界面,操作起来很容易。
本文介绍了一个基于Struts2、Spring2.5和Hibernate3.2的轻量级JavaEE配套解决方案。文章详细阐述了如何利用Spring的annotation配置简化XML配置文件,并通过具体的配置示例展示了如何实现这一目标。同时,还讨论了Hibernate使用annotation配置的优势及具体配置方法。
132

被折叠的 条评论
为什么被折叠?



