随笔-42  评论-578  文章-1  trackbacks-0

        基于Annotation的SSH整合开发,其实,并没有我当初想像中那么顺利。真正去做的时候,才发觉有许多问题。但不要紧,探索一下吧。在探索过程中学到知识,才是最重要的。
        言归正传,现在,我们加入Spring的支持:把spring-framework-2.5.5\dist中的spirng.jar引进我们项目的lib目录来,还要添加\lib\aspectj\下的两个jar包,以支持切面编程。
        必要的配置文件还是要的:
        applicationContext-common.xml

<?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:aop
="http://www.springframework.org/schema/aop"
    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/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"
>
            
    
<!-- 配置SessionFactory,由Spring容器来管理Hibernate -->
    
<!-- 非Annotation时,使用org.springframework.orm.hibernate3.LocalSessionFactoryBean,
        它注入实体类的方式是setMappingResources(),而Hibernate Annotation所用的映射方式
        不是mapping resource,而是mapping class,这就要用到LocalSessionFactoryBean的子类
        AnnotationSessionFactoryBean了.因为AnnotationSessionFactoryBean它支持实体的注入
        方式setAnnotatedClasses,即对应Hibernate中的mapping class.参见这两个类的源代码. 
-->
    
<bean id="sessionFactory"
        class
="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        
<property name="configLocation">
            
<value>classpath:hibernate.cfg.xml</value>
        
</property>
    
</bean>

    
<!-- 配置事务管理器 -->
    
<bean id="transactionManager"
        class
="org.springframework.orm.hibernate3.HibernateTransactionManager">
        
<property name="sessionFactory">
            
<ref bean="sessionFactory" />
        
</property>
    
</bean>
    
    
<!-- 配置事务的传播特性 -->
    
<tx:advice id="txAdvice" transaction-manager="transactionManager">
        
<tx:attributes>
            
<tx:method name="save*" propagation="REQUIRED" />
            
<tx:method name="update*" propagation="REQUIRED" />
            
<tx:method name="delete*" propagation="REQUIRED" />
            
<tx:method name="*" read-only="true" />
        
</tx:attributes>
    
</tx:advice>
    
    
    
<!-- 那些类的哪些方法参与事务 -->
    
<aop:config>
        
<aop:pointcut id="allServiceMethod" expression="execution(* com.rong.dao.*.*.*(..))" />
        
<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
    
</aop:config>
    
    
<!-- 使Spring关注Annotation -->
    
<context:annotation-config/>
    
    
<!-- 让Spring通过自动扫描来查询和管理Bean -->
    
<context:component-scan base-package="com.rong"/>
    
    
<!-- 
    <bean id="userDao" class="com.rong.dao.UserDaoBean">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <bean id="userService" class="com.rong.service.UserServiceBean">
        <property name="userDao" ref="userDao"/>
    </bean>
     
-->
    
</beans>

        关键的两点:

    <!-- 使Spring关注Annotation -->
    
<context:annotation-config/>
    
    
<!-- 让Spring通过自动扫描来查询和管理Bean -->
    
<context:component-scan base-package="com.rong"/>

        这样配置之后,就省去了上面注释掉的DAO层和Service层等配置代码。是不是很方便呢。
       关于这一部分的XML代码,我们下面还会作解释。

        来开发我们的DAO层吧,接口如下:

package com.rong.dao;

import java.util.List;
import com.rong.entity.User;

public interface UserDao {
    
    
public void save(User user);
    
    
public void delete(int id);
    
    
public void update(User user);
    
    
public List<User> query();
    
    
public User get(int id);

}

        DAO层的实现类:
package com.rong.dao;

import java.util.List;
import org.springframework.stereotype.Repository;
import com.rong.entity.User;

@Repository(
"userDao")        //声明此类为数据持久层的类
public class UserDaoBean extends MyHibernateDaoSupport implements UserDao {
    
    
public void save(User user){
        
super.getHibernateTemplate().save(user);
    }

    
    
public void delete(int id){
        
super.getHibernateTemplate().delete(super.getHibernateTemplate().load(User.class, id));
    }

    
    
public void update(User user){
        
super.getHibernateTemplate().update(user);
    }

    
    @SuppressWarnings(
"unchecked")
    
public List<User> query(){
        
return super.getHibernateTemplate().find("from User");
    }

    
    
public User get(int id){
        
return (User)super.getHibernateTemplate().get("from User", id);
    }


}

        大家可以看到,我们这里继承的不是HibernateDaoSupport,而是我自己编写的一个类MyHibernateDaoSupport。其代码如下:
package com.rong.dao;

import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class MyHibernateDaoSupport extends HibernateDaoSupport {
    
    @Resource(name
="sessionFactory")    //为父类HibernateDaoSupport注入sessionFactory的值
    public void setSuperSessionFactory(SessionFactory sessionFactory){
        
super.setSessionFactory(sessionFactory);
    }


}
        我们之所以要改写HibernateDaoSupport,是因我为,我们要为DAO层的类注入SessionFactory这个属性。以后,我们开发的DAO类,就可以直接重用这个MyHibernateDaoSupport了。其实,这样做是相当于配置文件方式的代码:        
    <bean id="userDao" class="com.rong.dao.UserDaoBean">
        
<property name="sessionFactory" ref="sessionFactory"/>
    
</bean>
        我们既然要用annotation代替XML文件的,就要让它也能像原来那样使用sessionFactory,故为MyHibernateDaoSupport注入SessionFactory。子类继承这个类时,也继承其Annotation。这样,我们就可以实现SessionFactory的注入了。
         到现在,我们再回过头来看applicationContext-common.xml中的
    <bean id="sessionFactory"
        class
="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        
<property name="configLocation">
            
<value>classpath:hibernate.cfg.xml</value>
        
</property>
    
</bean>
        我们平时开发Hibernate与Spring整合时,常常会用到org.springframework.orm.hibernate3.LocalSessionFactoryBean来提供SessionFactory,而我们这里却要改成org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean。其实是这样的,我们在Hibernate.cfg.xml中配置的实体类映射的方式如下:(详见基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (1)
        <!--
        <mapping resource="com/rong/entity/User.hbm.xml"/>
         
-->
         
         
<!-- 在Hibernate中注册User实体类,区别于上面注释掉的resource写法 -->
         
<mapping class="com.rong.entity.User"/>
        要使Hibernate的实体类支持注解,去掉xxx.hbm.xml的文件,故我们所用的是mapping class方式,不是mapping resource的方法。然而,LocalSessionFactoryBean这个类,它采用的实体类映射方式是mapping resource,(详情可参见LocalSessionFactoryBean这个类的源代码)。如果我们在配置中仍然用这个类的话,Hibernate与Spring整合时,就会报错。而AnnotationSessionFactoryBean这个类在LocalSessionFactoryBean的基础上添加了mapping class方式实现实体类映射(详见AnnotationSessionFactoryBean类的源代码)。
        我们再来看Service层的代码:(接口比较简单,节约篇幅就不列出了)
package com.rong.service;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rong.dao.UserDao;
import com.rong.entity.User;

@Service(
"userService")        //声明此类为业务逻辑层的类
public class UserServiceBean implements UserService {
    
    @Autowired
    
private UserDao userDao;

    
public void save(User user){
        userDao.save(user);
    }


}
        我们用到的注解上面一般都作了注释,就不多叙。@Autowired和@Resource功能差不多,就是把对象注入,相当于<bean>配置的功能。
        好,就开发到这样,是不是忘记了什么?记得要配置web.xml,部分代码如下:
      <!-- 修改Spring配置文件的路径 -->
    
<context-param>
        
<param-name>contextConfigLocation</param-name>
        
<param-value>classpath*:applicationContext-*.xml</param-value>
    
</context-param>
    
    
<!-- 配置Spring -->
    
<listener>
        
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    
</listener>

        是不是真的成功了?用Junit测试一下吧,我测试过是没问题的,由于篇幅,Junit的测试代码就不贴出来了。自己练习一下吧!
        其实,到现在为止,我们发觉我们的XML配置文件还是很多。其实,这样想想,上一阶段我们省去了xxx.hbm.xml这类的文件,这一阶段,我们少去了<bean id="" class=""><property name="" ref="">这样的配置项。而这些,正是我们项目开发中,大量使用的配置。而只要书写简单的Annotation注解,就可以省去这样,我们何乐而不用。而那些我们保留的XML配置文件(如:数据库连接,事务),这样是写死的,一个项目就写一次或复制过来用,我们保留它又何妨?

        好,暂时到这里,我们还有下一阶段的基于Annotation的SSH整合开发,我们将会以一个用户注册的例子,把Struts2的注解带到我们的整合开发中来。一起期待吧!
        (*^-^*) 本文原创,转载请注明出处, http://www.blogjava.net/rongxh7谢谢! (*^-^*)

本文原创,转载请注明出处,谢谢!http://www.blogjava.net/rongxh7(心梦帆影JavaEE技术博客)
    

posted on 2009-03-25 01:05 心梦帆影 阅读(13088) 评论(24)  编辑  收藏 所属分类: Struts2.xHibernateSpring

评论:
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-03-25 09:17 | awed
对于在Hibernate上什么Annotation还比较好理解,但对于Spring的Service上使用就有点不理解了,对于多人协作开发的时候如何知道定义的DAO名呢,就像
@Autowired
private UserDao userDao;
如果我在DAO层上定义的@Repository("userDao")不是 userDao的名字,那么是否是按类型来匹配  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-03-25 14:37 | super2
<mapping class="com.rong.entity.User"/> 这个也应该零配置  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) [未登录] 2009-03-26 17:41 | wolf
严重支持中,加油~~你真的很不错~~  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-04-30 16:59 | baidu:aids514
仔细读了下你的文章,的确写的不错,看得出来你花了很多时间在这上面

呵呵,感谢和我们分享,谢谢。。

不过,读完,试完之后发现一些不足之处,呵呵,个人觉得,也不知道对不对

在测试的时候,发现程序运行好慢,远远没有spring2.0+hibernate3.2组合的

无注释运行的快,在web中还没来及测试,不知道效果怎么样。

楼主能否做个测试呢?评价下有\无注释的优与劣?

静候佳音....

有结果可以发到我邮箱,我们也可以交流下:dukai1008@163.com  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-04-30 17:11 | baidu:aids514
初步做了个测试

但是发不上来,说我的是广告,晕死了

从[Test] INFO [2009-04-30 17:07:36,984] 到 [Test] INFO [2009-04-30 17:07:43,796]

差不多用7秒之久,估计放到web中会快3到4秒

明天测试下,今天下班了,呵呵  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) [未登录] 2009-05-31 21:42 | hone
ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in file [E:\setupsoft\Tomcat5.5\webapps\ssh2\WEB-INF\classes\com\rong\dao\impl\UserDaoBean.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-05-31 23:54 | 心梦帆影
@hone
你有没有写MyHibernateDaoSupport类?  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) [未登录] 2009-06-02 14:06 | hone
有写MyHibernateDaoSupport这个类  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) [未登录] 2009-06-02 14:13 | hone
博主,我的邮箱是hone033@gmail.com,期待你的回复  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-06-08 09:54 | ufo
www.gm365.com上发布的web server软件UFO不会出现一个字节的内存泄漏和一个线程的不能回收,使用UFO做Web Server的好处是网站能做得很稳定,永远也不会自己down掉;UFO在托管机房丢包率很高、遭受Hacker攻击、互联网 骨干网被黑等恶劣的环境条件下仍然能很好地运行;UFO在对付Hacker方面(防Hacker弄down和Hacker抓取不该访问的资源)也有足 够措施。
另外,UFO几乎不会进行垃圾回收,消耗CPU很少,在普通的PC Server上用UFO运行网站,平时CPU占用率<0.1%,最多时也不会超 过5%。您知道,JVM的垃圾回收会导致大量的运算,消耗很多CPU,从而导致Server的负载能力和响应速度下降。UFO在对象管理方面采 用了很好的机制和算法,做得很出色。用UFO运行网站,可以一直保证高负载能力,快速的响应速度和低CPU消耗。
  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-06-13 20:09 | 吴丹勇
写的很好啊!受益良多!  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-07-28 22:53 | ynyee
@awed
他会根据你写的变量名获取到类型  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) [未登录] 2009-12-03 17:56 | a
在spring的配置文件中sessionFactory 为 AnnotationSessionFactoryBean,而在@Resource(name="sessionFactory")中使用的是org.hibernate.SessionFactory
是否有问题?这两个sessionFactory是什么关系?请指教
  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2009-12-04 23:11 | 心梦帆影
@a
因为在本文中,为了使用getHibernateTemplate()方法,我们不得不继承HibernateDaoSupport类,而在HibernateDaoSupport类中,有一个方法:
public final void setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
}
这是我们注入SessionFactory的入口方法,而既然我们采用了Annotation取代XML配置了,就需要HibernateDaoSupport类的setSessionFactory方法是加多一个注解:@Resource(value="sessionFactory")。
然而,我们不能直接修改Hibernate的源码,就只能继承它,正如上文中我写的MyHibernateDaoSupport类,再在MyHibernateDaoSupport类中通过super关键词为父类注入AnnotationSessionFactory.  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2010-02-08 15:04 | 人字
a  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2010-02-08 15:07 | 人字
你好~!我现在也在整合ssh,不过遇到很到问题~!看了你的杰作真是佩服~!但是我还是菜鸟,你没写的东西我都写不出来~!所以能不能麻烦你把整个项目的源码,还有Spring+hibernate整合的测试代码发给我啊?~!谢谢。。。  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2010-02-08 15:08 | 人字
不好意思!忘了写我的邮箱地址:346527107@qq.com ...无限感激  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2010-03-10 22:20 | 双目鱼
小弟佩服!!  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2010-05-22 21:48 | 游客
public final void setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
}


MyHibernateDaoSupport 居然能够 override setSessionFactory,神来之笔啊  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2010-07-13 23:53 |
<mapping class="com.rong.entity.User"/>


要是有上100个 实体,都得一个一个配么?  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2011-04-27 11:55 | daniu
@特
那就在实体类上也使用注解, 别用hbm.xml了
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- 依赖注入数据源,注入正是上面定义的dataSource -->
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.test.model</value>
</list>
</property>
</bean>

实体类直接注解即可
  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2011-07-19 14:38 | 鱼归不知处
你好!我现在正在整合SSH,看了你的文章,觉得非常不错,可自己现在还是个菜鸟,麻烦你能否把整合的源码发给我一份,万分感谢!!!邮箱地址:253366940@qq.com  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2011-09-01 09:42 | 钱塘江
您好,能把这个工程代码发我邮箱么,谢谢575955073@qq.com  回复  更多评论
  
# re: 基于Annotation的Struts2.0+Hibernate3.3+Spring2.5整合开发 (2) 2013-03-15 14:36 | kkkkksyou
@游客
大哥 你看清楚 哪个是override 么?  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: