使用的是IDEA 2016.2 社群免費版。已經内置了maven。也可以自定義為個人安裝的maven。
建立一個maven項目
File -> New -> Project,選擇maven項目。然後next,填個内容:

下一步:
完成。
編寫pom.xml和代碼
項目結構最終如下:
在pom.xml中加入如下内容:
<dependencies>
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
最終内容如下:
<?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>me.letiantian.learn</groupId>
<artifactId>learn</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
IDEA會自動使用maven(或者會有提示)下載下傳依賴。我們可以直接在自己的代碼裡使用這些依賴的庫了。
Util.java類的内容如下:
package me.letiantian.learn;
import com.github.kevinsawicki.http.HttpRequest;
public class Util {
public static int getRespCode(String url) {
String ua = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48";
HttpRequest request = HttpRequest.get(url).header("User-Agent", ua);
return request.code();
}
public static int add(int x, int y) {
return x+y;
}
// 在main函數裡測試一下
// 當然,最好是在UtilTest類中寫測試代碼
public static void main(String[] args) {
System.out.println(add(2,3));
}
}
UtilTest内容如下:
package me.letiantian.learn;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UtilTest {
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
@Test
public void testAdd() throws Exception {
assertEquals(3, Util.add(1,2));
}
@Test
public void testGetRespCode() throws Exception {
assertEquals(200, Util.getRespCode("http://www.oschina.net"));
}
}
運作和測試
在Util.java的編輯界面中右擊滑鼠,選擇“Run Util.main()”:
在UtilTest.java的編輯界面中右擊滑鼠,選擇“Run UtilTest”
使用maven
菜單中依次點選“View” ->“Tool Windows” -> “Maven projects”,會出現:
如果要在本機的其他項目中使用該項目,依次運作clean和install,maven會将生成的jar檔案打包到本機的maven庫中。在其他項目的pom.xml中加入以下内容即可:
<dependency>
<groupId>com.qq.weixin.pay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
版權聲明:本文為CSDN部落客「weixin_34405354」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:https://blog.csdn.net/weixin_34405354/article/details/92473604