以注解的方式,来进行SSH整合配置
- jar
1.为了使struts支持注解,需要用到struts2-convention-plugin-2.1.7.jar这个jar包
2.放在WEB-INF/lib 下
3. 不仅如此,还要在项目导入jar,以使得eclipse能够编译通过 - 修改applicationContext.xml
1. 增加注解配置,组建扫描,以及移动事务管理的配置到前面
2. 注释掉 action,service,dao<context:annotation-config /><!--spring 属性注入的配置--> <context:component-scan base-package="com.how2java" /><!--spring bean对象注入的配置--> <tx:annotation-driven transaction-manager="transactionManager"/><!--事务管理配置-->
3. 替换SessionFactory类
为org.springframework.orm.hibernate3.LocalSessionFactoryBean
以支持注解方式org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
4. 去掉
增加<property name="mappingResources"> <list> <value>com/how2java/pojo/Product.hbm.xml</value> </list> </property>
<property name="packagesToScan"> <list> <value>com.how2java.*</value> </list> </property>
<?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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <context:component-scan base-package="com.how2java" /> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- <bean name="productActionBean" class="com.how2java.action.ProductAction"> --> <!-- <property name="productService" ref="productServiceImpl" /> --> <!-- </bean> --> <!-- <bean name="productServiceImpl" class="com.how2java.service.impl.ProductServiceImpl"> --> <!-- <property name="productDAO" ref="productDAOImpl" /> --> <!-- </bean> --> <!-- <bean name="productDAOImpl" class="com.how2java.dao.impl.ProductDAOImpl"> --> <!-- <property name="sessionFactory" ref="sf" /> --> <!-- </bean> --> <bean name="sf" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="ds" /> <!-- <property name="mappingResources"> --> <!-- <list> --> <!-- <value>com/how2java/pojo/Product.hbm.xml</value> --> <!-- </list> --> <!-- </property> --> <!-- 注解扫描 --> <property name="packagesToScan"> <list> <value>com.how2java.*</value> </list> </property> <property name="schemaUpdate"> <value>true</value> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hbm2ddl.auto=update </value> </property> </bean> <bean name="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="admin" /> </bean> <!-- 配置事务管理器(声明式的事务) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sf"></property> </bean> </beans>
- 修改struts.xml
注释掉action配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <constant name="struts.objectFactory" value="spring"/> <package name="basicstruts" extends="struts-default"> <!-- <action name="listProduct" class="productActionBean" method="list"> --> <!-- <result name="listJsp">list.jsp</result> --> <!-- </action> --> </package> </struts>
- 为ProductAction添加注解
1. 配置Namespace,ParentPackage,Results
2. 使用@Autowired自动装配productService@Namespace("/") @ParentPackage("struts-default") @Results({@Result(name="listJsp", location="/list.jsp")})
3. 在list()方法前加注解 @Action("listProduct"),以映射路径
package com.how2java.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.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import com.how2java.pojo.Product; import com.how2java.service.ProductService; @Namespace("/") @ParentPackage("struts-default") @Results({@Result(name="listJsp", location="/list.jsp")}) public class ProductAction { @Autowired ProductService productService; List<Product> products; @Action("listProduct") public String list() { products = productService.list(); return "listJsp"; } public ProductService getProductService() { return productService; } public void setProductService(ProductService productService) { this.productService = productService; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } }
- 为ProductServiceImpl 添加注解
1. 使用@Service 为 ProductServiceImpl添加注解
2. 使用@Autowired自动装配productDAO
3. 注释掉故意抛出异常部分
// if(i==2)
// throw new RuntimeException();
package com.how2java.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.how2java.dao.ProductDAO; import com.how2java.pojo.Product; import com.how2java.service.ProductService; @Service public class ProductServiceImpl implements ProductService { @Autowired ProductDAO productDAO; @Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="Exception") public List<Product> list() { List<Product> products= productDAO.list(); if(products.isEmpty()){ for (int i = 0; i < 5; i++) { Product p = new Product(); p.setName("product " + i); productDAO.add(p); products.add(p); } } return products; } public ProductDAO getProductDAO() { return productDAO; } public void setProductDAO(ProductDAO productDAO) { this.productDAO = productDAO; } }
- 为ProductDAOImpl 添加注解
1. 使用Repository 为ProductDAOImpl 添加注解
2. 重写setSessionFactory方法,并使用@Resource(name="sf")对其注解,以接受sessionFactory注入( 在 applicationContext.xml中sessionFactory所取得id是sf)
为什么要重写?
虽然ProductDAOImpl 继承了HibernateTemplate ,有setSessionFactory方法,但是HibernateTemplate 中的setSessionFactory方法,并没有被注解,所以就不会被注入sf, 因此需要在这里重写这个方法。
package com.how2java.dao.impl; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import com.how2java.dao.ProductDAO; import com.how2java.pojo.Product; @Repository("productDAO") public class ProductDAOImpl extends HibernateTemplate implements ProductDAO{ @Resource(name="sf") public void setSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); }; public List<Product> list() { return find("from Product"); } @Override public void add(Product p) { save(p); } }
- 为Product添加注解
1. 使用@Entity 为 Product 添加注解
2. @Table 指定对应表名
3. @id 表明主键
4. @GeneratedValue(strategy = GenerationType.IDENTITY) 使用自增长策略
5. @Column 指明属性对应的数据库中的字段名
package com.how2java.pojo; 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 = "product_") public class Product { int id; String name; float price; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "price") public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
- 重启测试
重启后,访问地址
http://127.0.0.1:8080/ssh/listProduct
- @Repository和@Service注解时什么意思?
@Repository 表示这个是DAO层
@Service 表示这个是Service层
因为这种分层方式非常普遍,被大家广泛接受,所以Spring就用这个来作为注解名称把这些类纳入了Spring的管理,也方便记忆和分辨。