2017 年最流行、最好用的 Java 庫

原文地址:html

http://mp.weixin.qq.com/s?__biz=MzI1OTIyNzY3Mw==&mid=2247483753&idx=1&sn=2f9b1aa8f29436e6d2d1dabb1066d3f7&chksm=ea7d681fdd0ae109ff6cb218ab13700fd3764fd385fc692a6ca8418d687bb59fe9d292303517&mpshare=1&scene=23&srcid=0224J82AJOyRvpBg9HLPvckX#rdjava

文章介紹git

這篇文章介紹了2017 年最流行、最好用的 Java 庫,從事 Java 或 Android 開發的同窗不要錯過了。github

正文api

Guicepromise

Guice (發音同 juice) 是 Google 開發的一款適用於 Java 6+ 的依賴注入框架。安全

# 依賴注入方式public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {  @Inject Connection connection;  public TransactionLog get() {    return new DatabaseTransactionLog(connection);
  }
}
# FactoryModuleBuilder generates factory using your interfacepublic interface PaymentFactory {   Payment create(Date startDate, Money amount);
}
GitHub:https://github.com/google/guice
JavaDoc: https://google.github.io/guice/api-docs/latest/javadoc/index.html
網址:https://github.com/google/guice/wiki/Motivation
FactoryModuleBuilder:https://google.github.io/guice/api-docs/latest/javadoc/index.html服務器

 

 

OkHttp網絡

OkHttp 是目前很是流行的網絡請求框架。高效地執行 Http 請求可以讓你的數據加載更快、帶寬消耗更少。數據結構

OkHttp 的高效率來自如下幾個特性:

支持 HTTP/2;這容許全部對相同 host 的請求共用一個 socket;
若是尚未升級到 HTTP/2,OkHttp 內部的請求池也能減小你的請求延時;
GZIP 能壓縮數據下載體積;
對 Response 進行自動 cache 能夠加快重複請求的響應速度
OkHttpClient client = new OkHttpClient();String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();  return response.body().string();
}
GitHub:https://github.com/square/okhttp
網址:http://square.github.io/okhttp/

 

Retrofit

這是一款 Square 公司開發的針對 Android 和 Java 的類型安全 Http Client。Retrofit 能夠把你的 Http API 轉化爲 Java 接口。

public interface GitHubService {    @GET("users/{user}/repos")
    Call<List<Repo>listRepos(@Path("user") String user);
}
此處 Retrofit 會生成一個 GitHubService 的接口。

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);
利用這個接口,咱們能夠向遠程服務器直接執行同步或異步的 Http Request。

Call<List<Repo>> repos = service.listRepos("octocat");
GitHub:https://github.com/square/retrofit
網址:http://square.github.io/retrofit/

 

JDeferred

這是一款相似 JQuery 的 Java Deferred/Promise 庫,具有以下特性:

Deferred object and Promise
Promise 回調: .then(…), .done(…), .fail(…), .progress(…), .always(…)
Multiple promises: .when(p1, p2, p3, …).then(…)
Callable 和 Runnable: wrappers.when(new Runnable() {…})
使用 Executor Service
Java 範型支持: Deferred, deferred.resolve(10);, deferred.reject(new Exception());,deferred.notify(0.80);,
Android支持
Java 8 Lambda 友好

GitHub:https://github.com/jdeferred/jdeferred

網址:http://jdeferred.org/

 

RxJava

RxJava – JVM 的響應式擴展 – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.

它在觀察者模式的基礎上進行了擴展,支持 data/events 的序列化,增長了多種操做符來組裝數據序列,並且,你徹底不用關心底層的線程切換、同步機制、線程安全及併發數據結構。

RxJava 最廣爲人知的一種用法是:在後臺線程執行高密度計算工做、網絡請求等,而後回到 UI 主線程來顯示執行結果。

 Flowable.fromCallable(() -{
     Thread.sleep(1000); //  imitate expensive computation
     return "Done";
 })
   .subscribeOn(Schedulers.io())
   .observeOn(Schedulers.single())
   .subscribe(System.out::println, Throwable::printStackTrace);

 Thread.sleep(2000); // <--- wait for the flow to finish
GitHub:https://github.com/ReactiveX/RxJava
Wiki:https://github.com/ReactiveX/RxJava/wiki

 

MBassador

MBassador 是一款基於發佈-訂閱模式的輕量級、高性能的事件總線。它使用起來很是簡便,功能豐富,並且能夠自擴展來進一步提升性能、減小資源開銷。

MBassador 高性能的最關鍵緣由在於一種特殊的數據結構,這種數據結構可最大限度減少鎖競爭。

基於註解
同步/異步事件發佈
可配置引用類型
事件過濾
事件包裹
Handler優先級
自定義錯誤處理
擴展性
// Define your listener
class SimpleFileListener{
    [@Handler](https://my.oschina.net/u/994780)
    public void handle(File msg){
      // do something with the file
    }
}

// somewhere else in your code
MBassador bus = new MBassador();
Object listener = new SimpleFileListener();
bus.subscribe (listener);
bus.post(new File("/tmp/smallfile.csv")).now();
bus.post(new File("/tmp/bigfile.csv")).asynchronously();
網址:https://github.com/bennidi/mbassador
Javadoc:http://bennidi.github.io/mbassador/

 

Project Lombok

使用註解 annotation 來減小代碼重複,例如 getter、setter、not null檢查、生成 Builder 等。下面有一些 Project Lombok 的 feature:

val - 自動解析變量的返回類型,而且該變量是 final 類,如 final String foo = example.get(0); var foo = example.get(0);
[@NonNull](https://my.oschina.net/u/2981441) - 自動 check 非空並拋異常;
@Cleanup - 自動關閉資源,調用 close() 方法;
@Getter / @Setter - 不用再寫 public int getFoo() {return foo;} 了;
@ToString - 不用再開啓 Debugger 來看某個值了,它能自動生成一個 toString 方法;
@EqualsAndHashCode - 更方便地比較兩個對象是否相等;
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor - 自動按順序生成構造函數;
@Data - 同時包括 @ToString, @EqualsAndHashCode, @Getter 對全部變量, @Setter 對全部非 final 變量, @RequiredArgsConstructor

GitHub:https://github.com/rzwitserloot/lombok

網址:https://projectlombok.org/

 

Simple Logging Facade for Java (SLF4J)

The Simple Logging Facade for Java (SLF4J) 是一個日誌庫抽象層,並不是真正的日誌庫,能夠支持不一樣的日誌實現,如java.util.logging, logback, log4j。開發者能夠利用這個抽象層來隨時切換底層日誌實現框架。

實際上,SLF4J所提供的核心API是一些接口以及一個LoggerFactory的工廠類。在使用SLF4J的時候,不須要在代碼中或配置文件中指定你打算使用那個具體的日誌系統。SLF4J提供了統一的記錄日誌的接口,只要按照其提供的方法記錄便可,最終日誌的格式、記錄級別、輸出方式等經過具體日誌系統的配置來實現,所以能夠在應用中靈活切換日誌系統。

那麼何時使用SLF4J比較合適呢?

若是你開發的是類庫或者嵌入式組件,那麼就應該考慮採用SLF4J,由於不可能影響最終用戶選擇哪一種日誌系統。在另外一方面,若是是一個簡單或者獨立的應用,肯定只有一種日誌系統,那麼就沒有使用SLF4J的必要。假設你打算將你使用log4j的產品賣給要求使用JDK 1.4 Logging的用戶時,面對成千上萬的log4j調用的修改,相信這絕對不是一件輕鬆的事情。可是若是開始便使用SLF4J,那麼這種轉換將是很是輕鬆的事情。

網址:http://www.slf4j.org/
GitHub:https://github.com/qos-ch/slf4j
FAQ:https://www.slf4j.org/faq.html

 

JUnitParams

@Test
@Parameters({"17, false", 
             "22, true" })
public void personIsAdult(int age, boolean valid) throws Exception {
    assertThat(new Person(age).isAdult(), is(valid));
}
它的優點以下:

更加明顯 - 參數直接放在 test method 裏,而非 class 裏
更加簡潔 - 不須要構造函數來設置參數
參數能夠經過 csv String 或 parameters provider class 來提供

網址:http://pragmatists.github.io/JUnitParams

GitHub:https://github.com/Pragmatists/JUnitParams
Quickstart:https://github.com/Pragmatists/junitparams/wiki/Quickstart
Mockito

Tasty mocking framework for unit tests in Java

 //You can mock concrete classes, not just interfaces
 LinkedList mockedList = mock(LinkedList.class);

 //stubbing
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 //following prints "first"
 System.out.println(mockedList.get(0));

 //following throws runtime exception
 System.out.println(mockedList.get(1));

 //following prints "null" because get(999) was not stubbed
 System.out.println(mockedList.get(999));

 //Although it is possible to verify a stubbed invocation, usually it's just redundant  //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).  //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.  verify(mockedList).get(0); 網址:http://site.mockito.org/ GitHub:https://github.com/mockito/mockito 文檔:http://static.javadoc.io/org.mockito/mockito-core/2.7.9/org/mockito/Mockito.html)

相關文章
相關標籤/搜索