本文使用idea,Eclipse也類似
一、引言
0. 為何要使用maven?
公司項目目前遇到的問題:
-
版本管理混亂
版本多的時候,出現問題難以定位,為問題的排查和解決增加了很大的難度 -
項目過於復雜, 層次結構不夠清晰,顯得很臃腫,
不利於新同事理解業務 -
拉取項目代碼時,文件很大下載慢
在下載代碼的同時,要拉取幾百兆的依賴包 -
容易出現jar包沖突或者是缺少相應的依賴jar包
隨着需要的jar包越來越多, 每次引入jar包也需要小心翼翼, 說不准什么時候就會造成jar包沖突,
而且也很容易造成某個jar包依賴的jar包沒有引入而導致整個項目跑不起來
基於以上, 我們引入了maven
二、將普通java項目轉換為maven項目
1. 導入項目並新建pom.xml文件
鼠標右鍵: File -> open -> 選擇項目路徑;在項目的根目錄下創建pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.isoftstone.core</groupId>
<artifactId>isc</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>isc_env_dev</name>
<dependencies>
</dependencies>
<build>
<finalName>isc</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 按照maven項目目錄格式創建目錄結構
這里有以下兩個關鍵目錄:
a1. Java類文件標准目錄: src/main/java
a2. 資源文件(配置)標准目錄: src/main/resources
a3. js文件我的目錄: src/main/webapp(注意:最終要保證編譯打包好的文件結構與原始項目編譯打包后的文件結構一致)
注意:目錄需要標記為對應的目錄結構(選中目錄右鍵 Mark Directory as -> Sources Root (或Resources Root))
3. 生成maven項目依賴,並導入依賴
可以手動添加,但是我們的項目動輒上百個依賴包。
這里推介用大佬寫好的依賴生成的工具類實現,該工具類需要用到下面的一些工具類,因此,請先將下面的依賴項復制到pom.xml文件中。
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.3</version>
</dependency>
依賴生成工具類代碼如下,源地址請移步,使用方法是直接將該工具類添加到項目中,其中“lib”是您的jar文件的存放目錄的路徑:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.alibaba.fastjson.JSONObject;
public class MakePomFromJars {
public static void main(String[] args) throws FileNotFoundException, IOException {
Element dependencys = new DOMElement("dependencies");
File dir = new File("lib");
for (File jar : dir.listFiles()) {
JarInputStream jis = new JarInputStream(new FileInputStream(jar));
Manifest mainmanifest = jis.getManifest();
jis.close();
if (mainmanifest == null) {
System.err.println(jar.getName());
continue;
}
String bundleName = mainmanifest.getMainAttributes().getValue("Bundle-Name");
String bundleVersion = mainmanifest.getMainAttributes().getValue("Bundle-Version");
Element ele = null;
StringBuffer sb = new StringBuffer(jar.getName());
if (bundleName != null) {
bundleName = bundleName.toLowerCase().replace(" ", "-");
sb.append(bundleName + "\t").append(bundleVersion);
ele = getDependices(bundleName, bundleVersion);
// System.out.println(sb.toString());
// System.out.println(ele.asXML());
}
if (ele == null || ele.elements().size() == 0) {
bundleName = "";
bundleVersion = "";
String[] ns = jar.getName().replace(".jar", "").split("-");
for (String s : ns) {
if (Character.isDigit(s.charAt(0))) {
bundleVersion += s + "-";
} else {
bundleName += s + "-";
}
}
if (bundleVersion.endsWith("-")) {
bundleVersion = bundleVersion.substring(0, bundleVersion.length() - 1);
}
if (bundleName.endsWith("-")) {
bundleName = bundleName.substring(0, bundleName.length() - 1);
}
ele = getDependices(bundleName, bundleVersion);
sb.setLength(0);
sb.append(bundleName + "\t").append(bundleVersion);
// System.out.println(sb.toString());
// System.out.println(ele.asXML());
}
ele = getDependices(bundleName, bundleVersion);
if (ele.elements().size() == 0) {
ele.add(new DOMElement("groupId").addText("not find"));
ele.add(new DOMElement("artifactId").addText(bundleName));
ele.add(new DOMElement("version").addText(bundleVersion));
System.out.println(
sb.toString() + " not find, please visit https://mvnrepository.com/ to get more info.");
}
dependencys.add(ele);
// System.out.println();
}
System.out.println(dependencys.asXML());
}
public static Element getDependices(String key, String ver) {
Element dependency = new DOMElement("dependency");
// 設置代理
// System.setProperty("http.proxyHost", "127.0.0.1");
// System.setProperty("http.proxyPort", "8090");
try {
String url = "http://search.maven.org/solrsearch/select?q=a%3A%22" + key + "%22%20AND%20v%3A%22" + ver
+ "%22&rows=3&wt=json";
Document doc = Jsoup.connect(url).ignoreContentType(true).timeout(30000).get();
String elem = doc.body().text();
JSONObject response = JSONObject.parseObject(elem).getJSONObject("response");
if (response.containsKey("docs") && response.getJSONArray("docs").size() > 0) {
JSONObject docJson = response.getJSONArray("docs").getJSONObject(0);
Element groupId = new DOMElement("groupId");
Element artifactId = new DOMElement("artifactId");
Element version = new DOMElement("version");
groupId.addText(docJson.getString("g"));
artifactId.addText(docJson.getString("a"));
version.addText(docJson.getString("v"));
dependency.add(groupId);
dependency.add(artifactId);
dependency.add(version);
}
} catch (Exception e) {
e.printStackTrace();
}
return dependency;
}
}
運行結果:
使用時,只需要將運行結果字符串復制到pom.xml文件中。
注意:
項目依賴jar一般有三類,一類是公共jar,maven官網可以查到;第二類是公司自己的jar,第三類是第三方jar
a1. 當遇到not find,且是公共jar時,可以自己到maven官網上核實。
a2. 當遇到not find且不是公共jar,或者紅色不識別的,就是自有的一些jar。如果公司有搭建私服的需要把這些jar管理起來;否則可作為外部jar在pom中引入
4. 對項目進行編譯打包
- 項目上右鍵 Add Framework Support,選擇maven,點擊OK。在項目右側顯示MAVEN窗口
- 接下來執行mvn clean install 對項目進行編譯
5. 刪除多余的目錄
打包編譯成功之后,就可以把不必要的目錄干掉了! 主要是bin目錄和lib目錄
三、可能遇到的問題
1. 編譯打包都成功,項目運行起來當操作涉及到數據庫時,代碼報:invalid bound statement not found 錯誤
問題分析:這個問題出現在用xml配置mybatis的mapper時,找不到xml具體配置就會報這個錯
可能原因1:xml里面的namespace不對 或者id和mapper里面的方法名不一樣,或者parameterType對應不上,都會出現這種問題。找到錯誤的點修改
可能原因2:mapper寫在java目錄里了,編譯的時候這個xml文件並沒有被拉到target里面,
解決版本:找pom文件里面build節點下添加上:
<build>
<finalName>isc</finalName>
<!--解決Intellij構建項目時,target/classes目錄下不存在mapper.xml文件-->
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
<include>**/*.xls</include>
<include>**/*.xlsx</include>
</includes>
</resource>
</resources>
</build>