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

本文介绍在SSH框架中如何使用Spring注解进行集成与应用,包括导入相关包、配置Spring上下文、定义bean、实现事务管理及通过注解自动注入bean,并通过实际例子展示整合过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
<?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:jee="http://www.springframework.org/schema/jee" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <description>Spring公共配置 </description> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:cui"/> <property name="username" value="cui"/> <property name="password" value="cui"/> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.entity</value> </list> </property> </bean> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 使用annotation自动注入bean,并启动相关处理注解的进程 --> <context:component-scan base-package="com"> <context:include-filter type="regex" expression="com/.dao.*"/> <!-- 正则表达式必须格式正确,否则无效。以下是无效的示例 <context:exclude-filter type="regex" expression="/.service/..*"/> <context:exclude-filter type="regex" expression="com/.service*"/> <context:exclude-filter type="regex" expression=".service*"/> --> <!-- 正确格式:从base-package开始 <context:exclude-filter type="regex" expression="com/.service.*"/> <context:exclude-filter type="regex" expression="com/.service/..*"/> --> </context:component-scan> </beans>

web.xml

[c-sharp] view plain copy print ?
  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>
<?xml version="1.0" encoding="UTF-8"?> <web-app id="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>mytest</display-name> <!-- 指定spring配置文件的位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <!-- Struts 2 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <init-param> <param-name>actionPackages</param-name> <param-value>com.action</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 自动加载applicationContext --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>

使用Hibernate JPA定义User类:

[c-sharp] view plain copy print ?
  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. }
package com.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "s_user") public class User { private Long id; private String username; private String password; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "name") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name = "pwd") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }

Dao层:

[c-sharp] view plain copy print ?
  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. }
package com.dao; import com.entity.User; public interface UserDao { public void save(User user); } package com.dao.Impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import com.dao.UserDao; import com.entity.User; @Repository("userDao") public class UserDaoImpl implements UserDao { private HibernateTemplate template; private Log log = LogFactory.getLog(UserDaoImpl.class); //使用构造子注入自动注入sessionFactory @Autowired public UserDaoImpl(SessionFactory sessionFactory) { this.template = new HibernateTemplate(sessionFactory); } public void save(User user) { template.save(user); log.debug("save user:" + user.getUsername()); } }

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. }
package com.service; import com.entity.User; public interface UserManager { public void add(User user); } package com.service.Impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.UserDao; import com.entity.User; import com.service.UserManager; @Service("userManager") public class UserManagerImpl implements UserManager { //自动注入userDao,也可以使用@Resource @Autowired private UserDao userDao; private Log log = LogFactory.getLog(UserManagerImpl.class); public void add(User user) { userDao.save(user); log.debug("add User:" + user.getUsername()); } }

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. }
package com.action.convention; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.entity.User; import com.opensymphony.xwork2.ActionSupport; import com.service.UserManager; @Result(name = "success", location = "hello.jsp") public class UserAction extends ActionSupport { private static final long serialVersionUID = 1L; @Autowired private UserManager userManager; public String execute() { User user = new User(); user.setUsername("cuihaiyang"); user.setPassword("abcd"); userManager.add(user); return SUCCESS; } }

调试信息如下:

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>
<?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:jee="http://www.springframework.org/schema/jee" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <description>Spring公共配置 </description> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:cui"/> <property name="username" value="cui"/> <property name="password" value="cui"/> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.entity</value> </list> </property> </bean> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 使用annotation自动注入bean,并启动相关处理注解的进程 --> <context:component-scan base-package="com"> <context:include-filter type="regex" expression="com/.dao.*"/> <!-- 正则表达式必须格式正确,否则无效。以下是无效的示例 <context:exclude-filter type="regex" expression="/.service/..*"/> <context:exclude-filter type="regex" expression="com/.service*"/> <context:exclude-filter type="regex" expression=".service*"/> --> <!-- 正确格式:从base-package开始 <context:exclude-filter type="regex" expression="com/.service.*"/> <context:exclude-filter type="regex" expression="com/.service/..*"/> --> </context:component-scan> </beans>

web.xml

[c-sharp] view plain copy print ?
  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>
<?xml version="1.0" encoding="UTF-8"?> <web-app id="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>mytest</display-name> <!-- 指定spring配置文件的位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <!-- Struts 2 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <init-param> <param-name>actionPackages</param-name> <param-value>com.action</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 自动加载applicationContext --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>

使用Hibernate JPA定义User类:

[c-sharp] view plain copy print ?
  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. }
package com.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "s_user") public class User { private Long id; private String username; private String password; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "name") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name = "pwd") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }

Dao层:

[c-sharp] view plain copy print ?
  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. }
package com.dao; import com.entity.User; public interface UserDao { public void save(User user); } package com.dao.Impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import com.dao.UserDao; import com.entity.User; @Repository("userDao") public class UserDaoImpl implements UserDao { private HibernateTemplate template; private Log log = LogFactory.getLog(UserDaoImpl.class); //使用构造子注入自动注入sessionFactory @Autowired public UserDaoImpl(SessionFactory sessionFactory) { this.template = new HibernateTemplate(sessionFactory); } public void save(User user) { template.save(user); log.debug("save user:" + user.getUsername()); } }

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. }
package com.service; import com.entity.User; public interface UserManager { public void add(User user); } package com.service.Impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.UserDao; import com.entity.User; import com.service.UserManager; @Service("userManager") public class UserManagerImpl implements UserManager { //自动注入userDao,也可以使用@Resource @Autowired private UserDao userDao; private Log log = LogFactory.getLog(UserManagerImpl.class); public void add(User user) { userDao.save(user); log.debug("add User:" + user.getUsername()); } }

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. }
package com.action.convention; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.entity.User; import com.opensymphony.xwork2.ActionSupport; import com.service.UserManager; @Result(name = "success", location = "hello.jsp") public class UserAction extends ActionSupport { private static final long serialVersionUID = 1L; @Autowired private UserManager userManager; public String execute() { User user = new User(); user.setUsername("cuihaiyang"); user.setPassword("abcd"); userManager.add(user); return SUCCESS; } }

调试信息如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值