基於已構建S2SH項目配置全註解方式簡化設定檔,
如果還不熟悉s2sh項目搭建的朋友可以先閱讀
eclipse環境下基於tomcat-7.0.82構建struts2項目eclipse環境下基於已構建struts2項目整合spring+hibernate
這兩篇文章熟悉一下。
本文是基於以上兩篇文章的基礎構建的,以下給出全註解方式配置S2SH項目的參考步驟。
第一步:實體類映射資料庫表,簡化hibernate通過xml設定檔映射
首先我們建立實體類作為測試,包結構:
建立User到model包下,實體類欄位資訊如下所示:
package wjt.com.test.model;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;import org.hibernate.annotations.GenericGenerator;import java.util.Date;@Entity@Table(name="wjt_user")public class User { @Id @Column(name="ID",length=32) //主鍵建置原則 @GeneratedValue(generator = "paymentableGenerator") //hibernate的主鍵建置原則,name屬性與@GeneratedValue的generator = "paymentableGenerator"對應, //strategy 指定具體產生器的類名(指定建置原則) @GenericGenerator(name="paymentableGenerator",strategy="uuid") private String id; private String name; private String types; @Temporal(value=TemporalType.DATE) private Data date; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTypes() { return types; } public void setTypes(String types) { this.types = types; } }
hibernate各註解的用途及其屬性參考前輩的文章:
hibernate用註解配置實體類的映射
實體類準備完畢,我們需要將其交給hibernate工廠掃描映射到資料庫表,需要在hibernate的session工廠中配置packagesToScan屬性,給出applicationContect.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:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 資料來源配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/wjt_test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true" /> <property name="username" value="root" /> <property name="password" value="wujingtao" /> </bean> <!-- 配置hibernate session工廠 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 掃描實體類映射資料庫表的包 --> <property name="packagesToScan"> <list> <value>com.wjt.model</value> </list> </property> </bean></beans>
第二步:基於註解方式配置IOC
在原項目中service層、dao層中實作類別添加註解完成bean對spring容器的註冊,去掉採用set訪問器屬性注入的方式,增加註解聲明,代碼改寫如下:
dao層:
package wjt.com.test.dao.impl;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import wjt.com.test.dao.TestDaoI;@Repository("testDao")//這裡是bean註冊到spring容器public class TestDaoImpl implements TestDaoI{ @Autowired//這裡是將聲明的bean注入,其中sessionFactory依舊是在設定檔中註冊的 private SessionFactory sessionFactory; private Session getCurrentSession() { try { return sessionFactory.getCurrentSession(); } catch (HibernateException e) { return sessionFactory.openSession(); } } @Override public void testDaoMethod() { System.out.println("dao層測試方法..."); if(getCurrentSession()!=null) { System.out.println("session工廠注入成功!"); } } }
service層:
package wjt.com.test.service.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import wjt.com.test.dao.TestDaoI;import wjt.com.test.service.TestServiceI;@Service("testService")public class TestServiceImpl implements TestServiceI{ @Autowired private TestDaoI testDao; @Override public void testServiceMethod() { System.out.println("service層測試方法..."); testDao.testDaoMethod(); }}
action層:
package wjt.com.test.action;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.Namespace;import org.apache.struts2.convention.annotation.Result;import org.springframework.beans.factory.annotation.Autowired;import com.opensymphony.xwork2.ActionSupport;import wjt.com.test.service.TestServiceI;@Namespace("/")@Action(value = "testAction", results = { @Result(name = "success", location = "/index.jsp"), })public class TestAction extends ActionSupport { @Autowired private TestServiceI testService; public String execute() throws Exception { System.out.println("struts=========================="); testService.testServiceMethod(); return "success"; }}
TestAction類名上方的註解在後文中有解釋,這裡先掛問號。
到這裡還需要在applicationContext.xml中聲明spring對註解的支援以及spring容器對登入bean進行掃描完成屬性的注入從而達到控制反轉的目的,
在<beans></beans>節點下增加如下配置:
<!-- 註解支援 --> <context:annotation-config /> <!-- 掃描註冊bean並注入屬性 --> <context:component-scan base-package="wjt.com.**"></context:component-scan>
其中*號表示掃描wjt.com包及其子包下所有註冊的bean。到這裡spring+hibernate註解方式配置已全部完成,對上述註解不太熟悉的可以參考前輩文章:
Spring 註解詳解
第三步:struts2中action的註解方式配置
首先我們需要引入struts2對註解支援的jar包:
這個時候需要我們在TestAction類名上方添上剛才掛問號的註解,對於Action註解的解釋請參考:
Struts2註解詳解
我們這裡註解的意義為當TestAction中預設方法返回“success”時頁面跳轉到index.jsp
接著我們需要簡化struts2的設定檔,給出簡化後的設定檔如下:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><!-- 這裡要和struts2版本號碼統一 --><struts> <!-- 告知Struts2運行時使用Spring來建立對象 --> <constant name="struts.objectFactory" value="spring" /> <package name="default" namespace="/" extends="struts-default"> </package></struts>
第三步:測試
到這裡一個完整的基於全註解方式配置s2sh項目就完成了,啟動項目測試是否達到我們的要求:
一、項目啟動資料庫應當已建立一張wjt_user表
二、訪問TestAction時應當跳轉到index.jsp頁面
為了驗證測試我們在index.jsp的body標籤內寫入“這是Mr至簡的第一個全註解方式配置S2SH項目”。
啟動項目後資料庫如下:
瀏覽器地址欄輸入:http://localhost:8080/SSHDemo/testAction 請求後如下:
以上就是關於S2SH項目全註解配置的參考方案,有不合理的地方還請各位讀者指出。