Maven專案環境搭建(Maven + Spring + IBatis)步驟
準備步驟
1. 安裝Maven,下載解壓即可。官網下載
2. 修改maven_home/conf/settings.xml中的<localRepository>D:/MavenRepo</localRepository>指定本地倉庫位置,這個位置是本地計算機上用來存放所有jar包的地方。
3. 修改settings.xml中的<mirrors></mirrors>標籤,新增常用的maven遠端倉庫地址。這些倉庫地址就是用來下載jar包的時候用的。由於中央倉庫的訪問速度較慢(或者因為某些原因導致你根本不能訪問),因此一般需要設定其他的倉庫地址以提高訪問速度。比如:
<mirror>
<id>oschina</id>
<mirrorOf>central</mirrorOf>
<url>http://maven.oschina.net/content/groups/public/</url>
</mirror>
<mirror >
<id>repo2</id>
<mirrorOf>central</mirrorOf>
<url>http://repo2.maven.org/maven2/</url>
</mirror>
<mirror>
<id >net-cn</id>
<mirrorOf>central</mirrorOf>
<url>http://maven.net.cn/content/groups/public/</url>
</mirror>
如果使用mvn命令列來建立、構建和執行maven專案,則需要配置環境變數,路徑指向maven_home/bin即可。配置好後,可以檢視mvn命令:
由於使用命令太麻煩而且難記,我直接使用Eclipse的maven外掛來建立和執行maven專案。
4. 在Eclipse中整合Maven。
先安裝Eclipse的maven外掛(具體過程網上一大堆,比如:安裝Eclipse Maven外掛的幾種方法)
在Eclipse中通過Windows->Preferences->Maven選單下指定安裝的maven:
並指定自己的配置檔案settings.xml:
建立Maven專案
5. New->Maven Project->Next,選擇webapp型別的專案結構。由於不同型別的專案有不同的專案結構,因此Maven自帶了很多套專案骨架(archetype),這裡我們選擇webapp型別的骨架即可:
6. 輸入Group ID, Artifact ID, Version和Package, Finish.
7. 建立好後如圖,預設情況下已經將junit3.8匯入到專案中:
8. 先把預設使用的JRE環境替換成當前Eclipse中使用的JRE環境。
9. 每個Maven專案都有一個pom.xml檔案,這個檔案描述了這個專案的依賴關係,以及自身的一些屬性,包括properties的定義,以及Maven Modules的版本宣告,父模組以及子模組的名字等。同時這個檔案還包括了該專案在構建過程中做的事情的定義。現在開啟這個pom.xml檔案,先在<dependencies>標籤上方新增該專案用到的屬性定義(為了集中管理spring的版本,因此將其定義為屬性,在依賴spring的jar包時直接使用這個屬性即可):
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.0.RELEASE</spring.version>
</properties>
並在<dependencies></dependencies>標籤中新增如下依賴關係,其他的內容無需修改:
<dependencies>
<!-- MyBatis相關 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
<!-- MySQL相關 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Spring相關,這裡的spring.version就是上方宣告的版本號,這樣引用更方便修改和維護 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-ibatis</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 測試相關 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Servlet相關 -->
<dependency>
<groupId>tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>5.5.23</version>
</dependency>
<!-- Log相關 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
10. 在Maven的世界中,每一個jar包都可以通過Group ID, Artifact ID, Version這三個欄位(一般簡寫為GAV)來唯一定位,因此如果需要使用哪個jar包,只需要提供這三個欄位即可。
如果不知道版本號或者GroupID,可以去公共的Maven倉庫搜尋關鍵字。比如搜尋:log4j,即可出現倉庫中已經收錄的關於log4j的jar包:
如圖,我在oschina提供的maven庫中搜索log4j,出現了一些可用的jar包列表(這裡需要注意:有些jar包名稱看上去很相近,因此需要注意區別,選擇正確的jar包)。選擇某一個,右下方會有該包的GAV屬性。直接將這一段拷貝到maven專案pom.xml檔案中即可。
還有一個很好用的maven倉庫地址,推薦給大家:http://mvnrepository.com/
11. Jar包準備完畢後,開始專案介面的定義了。修改後的結構如圖:
12. web.xml僅僅定義了基本的DispatchServlet,用於轉發請求:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
13. spring.xml(xml頭有點冗餘,如果覺得用不到,可以刪除相應的xmlns和schemaLocation宣告)
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.abc" />
<!-- 屬性注入器,用於讀取專案配置檔案中的屬性 -->
<bean id="PropertiesConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:log4j.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- 資料來源,不需要解釋 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="mapperLocations"
value="classpath*:com/abc/dao/*.xml" /> -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!-- Mybatis sql session -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- Mybatis mapper scanner, scans for java mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.abc.dao" />
<property name="sqlSessionTemplateBeanName" value="sqlSession" />
</bean>
</beans>
14. log4j.properties,用於定義Log4j的日誌輸出內容及格式,我這裡就不湊字數了。
jdbc.properties,上方的配置中引用到的關於資料庫的配置,請在這個檔案中配置。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://192.168.12.1\:3306/abc?useUnicode\=true&characterEncoding\=UTF-8
jdbc.username=abc
jdbc.password=abc123_
15. mybatis-config.xml檔案,這裡面指定了哪些xml檔案可以作為DAO介面的對映檔案:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC
"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="com/abc/entity/UserMap.xml"/>
</mappers>
</configuration>
16. UserMap.xml檔案定義了對於User物件的操作的sql語句:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"
<mapper namespace="com.abc.dao.TestDao">
<resultMap id="UserResultMap" type="com.abc.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="name" />
<result column="userAge" jdbcType="INTEGER" property="age" />
<result column="userAddress" jdbcType="VARCHAR" property="address" />
</resultMap>
<select id="testQuery" resultMap="UserResultMap">
SELECT * FROM user
</select>
</mapper>
17. Controller, Service和DAO的宣告,都是很標準很簡單的Controller呼叫Service,Service再呼叫DAO介面的過程。
TestDao(完成資料讀寫):
package com.abc.dao;
import java.util.List;
import com.abc.entity.User;
public interface TestDao {
public List<User> testQuery() throws Exception;
}
TestService(介面程式設計,在面向多實現的時候非常有用):
package com.abc.service;
public interface TestService {
public String testQuery() throws Exception;
}
TestServiceImpl(完成主要的業務邏輯):
package com.abc.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.abc.dao.TestDao;
import com.abc.entity.User;
import com.abc.service.TestService;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestDao dao;
public String testQuery() throws Exception {
List<User> users = dao.testQuery();
String res = "";
if (users != null && users.size() > 0) {
for (User user : users) {
res += user.toString() + "|";
}
} else {
res = "Not found.";
}
return res;
}
}
TestController(完成請求轉發,響應封裝):
package com.abc.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.abc.service.TestService;
@Controller
@RequestMapping("/testController")
public class TestController {
public static final Logger LOGGER = Logger.getLogger(TestController.class);
@Autowired
private TestService testService;
@RequestMapping("/test")
public void test(HttpServletRequest request, HttpServletResponse response) {
try {
String result = testService.testQuery();
response.getWriter().print(result);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
程式碼部分到此就結束了。
構建和執行
18. 編寫好以後,在專案上右鍵->Run As->Maven Build…準備構建這個maven專案。
19. 在BaseDirectory中指定需要構建的專案(點選圖中的Brose Workspace或Browse File System按鈕可以選擇),並在Goals框中指定構建的目標(Maven有自己的構建的階段,有的地方又叫生命週期,如果不清楚的同學,可以參看Maven生命週期詳解)。並可以選擇一些附加的屬性(綠色框中),如圖:
20. 如果構建成功,則會出現類似於下面的輸出:
21. 當構建成功後,可以像普通的Web Project一樣來執行這個專案。這裡將其新增到Tomcat中,並啟動之。
22. 先看看資料庫的內容:
23. 在瀏覽器中訪問指定的介面,檢視結果(在我的實現類TestServiceImpl中,僅僅是列印了查詢到的結果):
附:例子下載:AbcDemo.zip
連結: http://pan.baidu.com/s/1pJ3pSBT 密碼: 3gpt