`

SSH下使用Spring注解自动注入bean

 
阅读更多

Spring注解的使用方法详见:http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/,这里在SSH框架下做一个例子。

首先导入相关包:spring-beans-3.0.4.RELEASE.jar(org.springframework.beans.factory.annotation.Autowired用来注入bean)、spring-context-3.0.4.RELEASE.jar(org.springframework.stereotype.Componet 、Service、Repository等用来定义bean)。

其次需要添加相关配置:applicationContext.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd">
  6. <description>Spring公共配置</description>
  7. <!--配置数据源-->
  8. <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
  9. <propertyname="driverClassName"value="oracle.jdbc.driver.OracleDriver"/>
  10. <propertyname="url"value="jdbc:oracle:thin:@127.0.0.1:1521:cui"/>
  11. <propertyname="username"value="cui"/>
  12. <propertyname="password"value="cui"/>
  13. </bean>
  14. <!--配置sessionFactory-->
  15. <beanid="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  16. <propertyname="dataSource"ref="dataSource"/>
  17. <propertyname="hibernateProperties">
  18. <props>
  19. <propkey="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
  20. <propkey="hibernate.show_sql">true</prop>
  21. </props>
  22. </property>
  23. <propertyname="packagesToScan">
  24. <list>
  25. <value>com.entity</value>
  26. </list>
  27. </property>
  28. </bean>
  29. <!--事务管理-->
  30. <beanid="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  31. <propertyname="sessionFactory"ref="sessionFactory"></property>
  32. </bean>
  33. <!--使用annotation自动注入bean,并启动相关处理注解的进程-->
  34. <context:component-scanbase-package="com">
  35. <context:include-filtertype="regex"expression="com/.dao.*"/>
  36. <!--正则表达式必须格式正确,否则无效。以下是无效的示例
  37. <context:exclude-filtertype="regex"expression="/.service/..*"/>
  38. <context:exclude-filtertype="regex"expression="com/.service*"/>
  39. <context:exclude-filtertype="regex"expression=".service*"/>
  40. -->
  41. <!--正确格式:从base-package开始
  42. <context:exclude-filtertype="regex"expression="com/.service.*"/>
  43. <context:exclude-filtertype="regex"expression="com/.service/..*"/>
  44. -->
  45. </context:component-scan>
  46. </beans>

web.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appid="WebApp_ID"version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  3. <display-name>mytest</display-name>
  4. <!--指定spring配置文件的位置-->
  5. <context-param>
  6. <param-name>contextConfigLocation</param-name>
  7. <param-value>classpath*:/applicationContext.xml</param-value>
  8. </context-param>
  9. <!--Struts2-->
  10. <filter>
  11. <filter-name>struts2</filter-name>
  12. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  13. <init-param>
  14. <param-name>actionPackages</param-name>
  15. <param-value>com.action</param-value>
  16. </init-param>
  17. </filter>
  18. <filter-mapping>
  19. <filter-name>struts2</filter-name>
  20. <url-pattern>/*</url-pattern>
  21. </filter-mapping>
  22. <!--自动加载applicationContext-->
  23. <listener>
  24. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  25. </listener>
  26. </web-app>

使用Hibernate JPA定义User类:

  1. packagecom.entity;
  2. importjavax.persistence.Column;
  3. importjavax.persistence.Entity;
  4. importjavax.persistence.GeneratedValue;
  5. importjavax.persistence.GenerationType;
  6. importjavax.persistence.Id;
  7. importjavax.persistence.Table;
  8. @Entity
  9. @Table(name="s_user")
  10. publicclassUser{
  11. privateLongid;
  12. privateStringusername;
  13. privateStringpassword;
  14. @Id
  15. @GeneratedValue(strategy=GenerationType.AUTO)
  16. publicLonggetId(){
  17. returnid;
  18. }
  19. publicvoidsetId(Longid){
  20. this.id=id;
  21. }
  22. @Column(name="name")
  23. publicStringgetUsername(){
  24. returnusername;
  25. }
  26. publicvoidsetUsername(Stringusername){
  27. this.username=username;
  28. }
  29. @Column(name="pwd")
  30. publicStringgetPassword(){
  31. returnpassword;
  32. }
  33. publicvoidsetPassword(Stringpassword){
  34. this.password=password;
  35. }
  36. }

Dao层:

  1. packagecom.dao;
  2. importcom.entity.User;
  3. publicinterfaceUserDao{
  4. publicvoidsave(Useruser);
  5. }
  6. packagecom.dao.Impl;
  7. importorg.apache.commons.logging.Log;
  8. importorg.apache.commons.logging.LogFactory;
  9. importorg.hibernate.SessionFactory;
  10. importorg.springframework.beans.factory.annotation.Autowired;
  11. importorg.springframework.orm.hibernate3.HibernateTemplate;
  12. importorg.springframework.stereotype.Repository;
  13. importcom.dao.UserDao;
  14. importcom.entity.User;
  15. @Repository("userDao")
  16. publicclassUserDaoImplimplementsUserDao{
  17. privateHibernateTemplatetemplate;
  18. privateLoglog=LogFactory.getLog(UserDaoImpl.class);
  19. //使用构造子注入自动注入sessionFactory
  20. @Autowired
  21. publicUserDaoImpl(SessionFactorysessionFactory){
  22. this.template=newHibernateTemplate(sessionFactory);
  23. }
  24. publicvoidsave(Useruser){
  25. template.save(user);
  26. log.debug("saveuser:"+user.getUsername());
  27. }
  28. }

Service层:

  1. packagecom.service;
  2. importcom.entity.User;
  3. publicinterfaceUserManager{
  4. publicvoidadd(Useruser);
  5. }
  6. packagecom.service.Impl;
  7. importorg.apache.commons.logging.Log;
  8. importorg.apache.commons.logging.LogFactory;
  9. importorg.springframework.beans.factory.annotation.Autowired;
  10. importorg.springframework.stereotype.Service;
  11. importcom.dao.UserDao;
  12. importcom.entity.User;
  13. importcom.service.UserManager;
  14. @Service("userManager")
  15. publicclassUserManagerImplimplementsUserManager{
  16. //自动注入userDao,也可以使用@Resource
  17. @Autowired
  18. privateUserDaouserDao;
  19. privateLoglog=LogFactory.getLog(UserManagerImpl.class);
  20. publicvoidadd(Useruser){
  21. userDao.save(user);
  22. log.debug("addUser:"+user.getUsername());
  23. }
  24. }

Action:

  1. packagecom.action.convention;
  2. importorg.apache.struts2.convention.annotation.Result;
  3. importorg.springframework.beans.factory.annotation.Autowired;
  4. importcom.entity.User;
  5. importcom.opensymphony.xwork2.ActionSupport;
  6. importcom.service.UserManager;
  7. @Result(name="success",location="hello.jsp")
  8. publicclassUserActionextendsActionSupport{
  9. privatestaticfinallongserialVersionUID=1L;
  10. @Autowired
  11. privateUserManageruserManager;
  12. publicStringexecute(){
  13. Useruser=newUser();
  14. user.setUsername("cuihaiyang");
  15. user.setPassword("abcd");
  16. userManager.add(user);
  17. returnSUCCESS;
  18. }
  19. }

调试信息如下:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into s_user (pwd, name, id) values (?, ?, ?)
2011-03-10 19:44:25,296 [http-8080-1] DEBUG [com.dao.Impl.UserDaoImpl] - save user:cuihaiyang
2011-03-10 19:44:25,296 [http-8080-1] DEBUG [com.service.Impl.UserManagerImpl] - add User:cuihaiyang

Spring注解的使用方法详见:http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/,这里在SSH框架下做一个例子。

首先导入相关包:spring-beans-3.0.4.RELEASE.jar(org.springframework.beans.factory.annotation.Autowired用来注入bean)、spring-context-3.0.4.RELEASE.jar(org.springframework.stereotype.Componet 、Service、Repository等用来定义bean)。

其次需要添加相关配置:applicationContext.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd">
  6. <description>Spring公共配置</description>
  7. <!--配置数据源-->
  8. <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
  9. <propertyname="driverClassName"value="oracle.jdbc.driver.OracleDriver"/>
  10. <propertyname="url"value="jdbc:oracle:thin:@127.0.0.1:1521:cui"/>
  11. <propertyname="username"value="cui"/>
  12. <propertyname="password"value="cui"/>
  13. </bean>
  14. <!--配置sessionFactory-->
  15. <beanid="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  16. <propertyname="dataSource"ref="dataSource"/>
  17. <propertyname="hibernateProperties">
  18. <props>
  19. <propkey="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
  20. <propkey="hibernate.show_sql">true</prop>
  21. </props>
  22. </property>
  23. <propertyname="packagesToScan">
  24. <list>
  25. <value>com.entity</value>
  26. </list>
  27. </property>
  28. </bean>
  29. <!--事务管理-->
  30. <beanid="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  31. <propertyname="sessionFactory"ref="sessionFactory"></property>
  32. </bean>
  33. <!--使用annotation自动注入bean,并启动相关处理注解的进程-->
  34. <context:component-scanbase-package="com">
  35. <context:include-filtertype="regex"expression="com/.dao.*"/>
  36. <!--正则表达式必须格式正确,否则无效。以下是无效的示例
  37. <context:exclude-filtertype="regex"expression="/.service/..*"/>
  38. <context:exclude-filtertype="regex"expression="com/.service*"/>
  39. <context:exclude-filtertype="regex"expression=".service*"/>
  40. -->
  41. <!--正确格式:从base-package开始
  42. <context:exclude-filtertype="regex"expression="com/.service.*"/>
  43. <context:exclude-filtertype="regex"expression="com/.service/..*"/>
  44. -->
  45. </context:component-scan>
  46. </beans>

web.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appid="WebApp_ID"version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  3. <display-name>mytest</display-name>
  4. <!--指定spring配置文件的位置-->
  5. <context-param>
  6. <param-name>contextConfigLocation</param-name>
  7. <param-value>classpath*:/applicationContext.xml</param-value>
  8. </context-param>
  9. <!--Struts2-->
  10. <filter>
  11. <filter-name>struts2</filter-name>
  12. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  13. <init-param>
  14. <param-name>actionPackages</param-name>
  15. <param-value>com.action</param-value>
  16. </init-param>
  17. </filter>
  18. <filter-mapping>
  19. <filter-name>struts2</filter-name>
  20. <url-pattern>/*</url-pattern>
  21. </filter-mapping>
  22. <!--自动加载applicationContext-->
  23. <listener>
  24. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  25. </listener>
  26. </web-app>

使用Hibernate JPA定义User类:

  1. packagecom.entity;
  2. importjavax.persistence.Column;
  3. importjavax.persistence.Entity;
  4. importjavax.persistence.GeneratedValue;
  5. importjavax.persistence.GenerationType;
  6. importjavax.persistence.Id;
  7. importjavax.persistence.Table;
  8. @Entity
  9. @Table(name="s_user")
  10. publicclassUser{
  11. privateLongid;
  12. privateStringusername;
  13. privateStringpassword;
  14. @Id
  15. @GeneratedValue(strategy=GenerationType.AUTO)
  16. publicLonggetId(){
  17. returnid;
  18. }
  19. publicvoidsetId(Longid){
  20. this.id=id;
  21. }
  22. @Column(name="name")
  23. publicStringgetUsername(){
  24. returnusername;
  25. }
  26. publicvoidsetUsername(Stringusername){
  27. this.username=username;
  28. }
  29. @Column(name="pwd")
  30. publicStringgetPassword(){
  31. returnpassword;
  32. }
  33. publicvoidsetPassword(Stringpassword){
  34. this.password=password;
  35. }
  36. }

Dao层:

  1. packagecom.dao;
  2. importcom.entity.User;
  3. publicinterfaceUserDao{
  4. publicvoidsave(Useruser);
  5. }
  6. packagecom.dao.Impl;
  7. importorg.apache.commons.logging.Log;
  8. importorg.apache.commons.logging.LogFactory;
  9. importorg.hibernate.SessionFactory;
  10. importorg.springframework.beans.factory.annotation.Autowired;
  11. importorg.springframework.orm.hibernate3.HibernateTemplate;
  12. importorg.springframework.stereotype.Repository;
  13. importcom.dao.UserDao;
  14. importcom.entity.User;
  15. @Repository("userDao")
  16. publicclassUserDaoImplimplementsUserDao{
  17. privateHibernateTemplatetemplate;
  18. privateLoglog=LogFactory.getLog(UserDaoImpl.class);
  19. //使用构造子注入自动注入sessionFactory
  20. @Autowired
  21. publicUserDaoImpl(SessionFactorysessionFactory){
  22. this.template=newHibernateTemplate(sessionFactory);
  23. }
  24. publicvoidsave(Useruser){
  25. template.save(user);
  26. log.debug("saveuser:"+user.getUsername());
  27. }
  28. }

Service层:

  1. packagecom.service;
  2. importcom.entity.User;
  3. publicinterfaceUserManager{
  4. publicvoidadd(Useruser);
  5. }
  6. packagecom.service.Impl;
  7. importorg.apache.commons.logging.Log;
  8. importorg.apache.commons.logging.LogFactory;
  9. importorg.springframework.beans.factory.annotation.Autowired;
  10. importorg.springframework.stereotype.Service;
  11. importcom.dao.UserDao;
  12. importcom.entity.User;
  13. importcom.service.UserManager;
  14. @Service("userManager")
  15. publicclassUserManagerImplimplementsUserManager{
  16. //自动注入userDao,也可以使用@Resource
  17. @Autowired
  18. privateUserDaouserDao;
  19. privateLoglog=LogFactory.getLog(UserManagerImpl.class);
  20. publicvoidadd(Useruser){
  21. userDao.save(user);
  22. log.debug("addUser:"+user.getUsername());
  23. }
  24. }

Action:

  1. packagecom.action.convention;
  2. importorg.apache.struts2.convention.annotation.Result;
  3. importorg.springframework.beans.factory.annotation.Autowired;
  4. importcom.entity.User;
  5. importcom.opensymphony.xwork2.ActionSupport;
  6. importcom.service.UserManager;
  7. @Result(name="success",location="hello.jsp")
  8. publicclassUserActionextendsActionSupport{
  9. privatestaticfinallongserialVersionUID=1L;
  10. @Autowired
  11. privateUserManageruserManager;
  12. publicStringexecute(){
  13. Useruser=newUser();
  14. user.setUsername("cuihaiyang");
  15. user.setPassword("abcd");
  16. userManager.add(user);
  17. returnSUCCESS;
  18. }
  19. }

调试信息如下:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into s_user (pwd, name, id) values (?, ?, ?)
2011-03-10 19:44:25,296 [http-8080-1] DEBUG [com.dao.Impl.UserDaoImpl] - save user:cuihaiyang
2011-03-10 19:44:25,296 [http-8080-1] DEBUG [com.service.Impl.UserManagerImpl] - add User:cuihaiyang

分享到:
评论

相关推荐

    ssh2注解配置

    ssh2注解配置,全部是注解配置,struts2和hibernate3和spring2.5全部是注解配置,,访问路径为http://localhost:8080/mytest/student/findAll.action

    struts2+spring+hibernate整合示例

    1 首先整合spring和hibernate,这次我们在spring 中配置bean使用注解的方式 ,hibernate实体映射关系也使用注解的方式,配置完毕后用简单方法测试下hibernate是否整合成功。 a 加入支持:添加 spring核心包、...

    IDEA下maven管理的SSH框架 spring4 + struts2 + hibernate3 小人员管理网站

    一个小型maven管理的ssh框架开发的人员管理网站,能基本对与ssh框架有一个基本了解,内容也不多,框架条理都分好了,易于学习。...默认字符集为UTF-8,数据库直接按照bean创建就行,注解形式无法自动创建表

    跟我学spring3(8-13)

    【第十二章】零配置 之 12.2 注解实现Bean依赖注入 ——跟我学spring3 【第十二章】零配置 之 12.3 注解实现Bean定义 ——跟我学spring3 【第十二章】零配置 之 12.4 基于Java类定义Bean配置元数据 ——跟我学spring...

    Spring的学习笔记

    一、 开始使用annotation配置Spring 16 二、 @Autowired、@Qualifier 16 (一) @Autowired 16 (二) @Qualifier 17 三、 @Resource(重要、推荐) 17 (一) JSR-250 17 (二) @Resource 17 四、 @Componet 18 五、 @Scope...

    SpringMVC-SSH全注解

    &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt; &lt;value&gt;com.org.core.entity&lt;/value&gt; ${hibernate....

    JSP基于SSH2图书管理系统

    SSH2(Struts2 + Spring + Hibernate),标准SSH2框架,采用了基于注解方式管理bean和事务,使用poi进行excel批量导出

    spring五种事务配置demo

    测试spring事务管理 搭建了ssh框架的web工程 本工程用到的数据库表很简单 user(id, name) 可自行创建 本例所有的事务放在service层进行管理,方法中间抛出... 第5种方式:全注解 详见spring-core-transaction-5.xml

    双鱼林JSP基于SSH2图书管理系统源码 v1.0.rar

    图书类型:图书类别,类别名称,可借阅天数 图书:图书条形码,图书名称,图书所在类别,...采用技术: SSH2(Struts2 Spring Hibernate),标准SSH2框架,采用了基于注解方式管理bean和事务,使用poi进行excel批量导出

    spring2.5 学习笔记

    一、 开始使用annotation配置Spring 16 二、 @Autowired、@Qualifier 16 (一) @Autowired 16 (二) @Qualifier 17 三、 @Resource(重要、推荐) 17 (一) JSR-250 17 (二) @Resource 17 四、 @Componet 18 五、 @Scope...

    双鱼林JSP基于SSH2图书管理系统源码

    采用技术: SSH2(Struts2 + Spring + Hibernate),标准SSH2框架,采用了基于注解方式管理bean和事务,使用poi进行excel批量导出 图书类型:图书类别,类别名称,可借阅天数 图书:图书条形码,图书名称,图书所在...

    JavaEE开发的颠覆者SpringBoot实战[完整版].part3

    涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...

    204JSP基于SSH2图书管理系统升级版 | 毕业设计

    采用技术: SSH2(Struts2 + Spring + Hibernate),标准SSH2框架,采用了基于注解方式管理bean和事务,使用poi进行excel批量导出 图书类型:图书类别,类别名称,可借阅天数 图书:图书条形码,图书名称,图书所在...

    基于SSH2图书管理系统源码.7z

    图书类型:图书类别,类别名称,可借阅天数 图书:图书条形码,图书名称,图书所在类别...采用技术: SSH2(Struts2 + Spring + Hibernate),标准SSH2框架,采用了基于注解方式管理Bean和事务,使用Poi进行Excel批量导出

    搭建SSH框架的代码

    8.有全文检索工具类包含索引的创建、查询等,自动分页Bean,Excel读取/导出等功能、汉字转拼音,MD5加密,加密解密,图片转字符、字符转图片,IP检查,拦截器权限拦截,Struts2Utils类,Spring3Utils类,轻松搞定...

    Spring4总复习讲义[共四部分|pdf格式]

    pdf文档包括如下知识: 1.spring介绍 2.spring搭建 3.spring中的概念 4.配置文件详解 5.Bean的创建方式 6.注入方式 7.复杂属性注入 8.在WEB环境中使用Spring容器 9.注解代替xml配置 10. spring AOP开发 等等。

    SSH整合+struts convention插件小示例

    SSH整合+struts convention插件小示例 全程使用注解扫包,无struts action的配置文件,...Spring自动扫包来获取bean 数据库内容太简单,不再上传。 只是一个小实例。 请用MyEclipse导入项目。 我的版本是MyEclipse 2013

    spring2.5+hibernate3.3+struts1.3的整合

    一个spring2.5+hibernate3.3+struts1.3的整合的完整项目,该项目使用spring容器创建sessionFactory,管理struts ActionBean的创建,其中使用注解的方式创建实体Bean以及依赖注入和事务

    JavaEE开发的颠覆者SpringBoot实战[完整版].part2

    涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...

    ssh框架的整合(含完整JAR)

    一个简单的ssh框架整合,内含实现以下描述所有的基础包,此框架实现hibernate,struts在spring中的整合,另外开启了spring的注解功能,在实例化spring容器时,可对指定包可以扫描Bean的存在,实现所谓的零配置。

Global site tag (gtag.js) - Google Analytics