431、Java框架85 -【SSH - 整合 - 註解方式】 2020.12.07
目錄
0、SSH - 整合 - 註解方式
以註解的方式,來進行SSH整合配置
1、基於前面的教程
本章節延續上面的SSH 事務管理註解方式繼續,這樣的好處是目前的狀態,除了事務以外,其他都是XML配置方式。 大家就可以看到如何從XML配置方式轉換為註解方式,並最後達到一樣的效果。
2、jar
1. 為了使struts支援註解,需要用到struts2-convention-plugin-x.x.x.jar 這個jar包,在前面的教程中是沒有使用的,所以這裡需要從右側下載
2. 從右上角下載好了之後,放在WEB-INF/lib 下
3. 不僅如此,還要在專案匯入jar,以使得eclipse能夠編譯通過
3、修改applicationContext.xml
1. 增加註解配置,組建掃描,以及移動事務管理的配置到前面
<context:annotation-config />
<context:component-scan base-package="com.how2java" />
<tx:annotation-driven transaction-manager="transactionManager"/>
2. 註釋掉 action,service,dao
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>
4、修改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>
5、為ProductAction添加註解
1. 配置Namespace,ParentPackage,Results
@Namespace("/")
@ParentPackage("struts-default")
@Results({@Result(name="listJsp", location="/list.jsp")})
2. 使用@Autowired自動裝配productService
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;
}
}
6、為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;
}
}
7、為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);
}
}
8、為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;
}
}
9、重啟測試
重啟後,訪問地址
http://127.0.0.1:8080/ssh/listProduct