---
title: "java如何在Spring Boot中用web3j开始开发以太坊智能合约"
author: "it_node"
date: "2018-11-26T10:56:12Z"
tags: []
categories: ["编程语言"]
slug: "java-spring-boot-web3j"
draft: false
lastmod: "2018-11-26T10:56:12Z"
id: 2434324
url: "https://it-node.iteye.com/blog/2434324"
---

通过Spring的依赖注入将web3j集成到Spring Boot应用程序中。此处提供了示例应用程序：

```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
```

```
package org.web3j.examples;

import java.io.IOException;

import org.apache.http.conn.HttpHostConnectException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootWeb3jSampleApplicationTest {

    @Autowired
    private Web3jSampleService web3jSampleService;

    // This test will only run if you provide a real Ethereum client for web3j to connect to
    @Test(expected = HttpHostConnectException.class)
    public void testGetClientVersion() throws IOException {
        assertThat(web3jSampleService.getClientVersion()).startsWith("Geth/");
    }
}
```

要使用[这个github示例](https://github.com/web3j/examples/tree/master/spring-boot)，请创建一个新的Spring Boot应用程序，并包含以下依赖项：

Maven：

```
1
2
3
4
5
```

```
<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>web3j-spring-boot-starter</artifactId>
    <version>1.6.0</version>
</dependency>
```

Gradle:

```
1
```

```
compile ('org.web3j:web3j-spring-boot-starter:1.6.0')
```

现在，Spring可以为你提供web3j实例，如果你需要它们：

```
1
2
```

```
@Autowired
private Web3j web3j;
```

如果要通过HTTP连接到默认URL`http://localhost:8545`，则无需其他配置。

否则，只需在应用程序属性中添加端点的地址：

```
1
2
3
4
5
```

```
# An infura endpoint
web3j.client-address = https://rinkeby.infura.io/

# Or, an IPC endpoing
web3j.client-address = /path/to/file.ipc
```

### 管理客户端

如果你希望使用Parity和Geth共有的personal模块方法管理帐户，启用管理客户端：

```
1
```

```
web3j.admin-client = true
```

然后Spring可以注入管理客户端：

```
1
2
```

```
@Autowired
private Admin admin;
```

### HTTP客户端配置

某些以太坊操作所需的时间超过了web3j使用的OkHttp3库设置的默认HTTP超时。要配置这些超时，请设置`web3j httpTimeoutSeconds`属性：

```
1
```

```
web3j.httpTimeoutSeconds = 600
```

这将设置所有三个OkHttp3超时：`connect`，`read`，`write`。

有效值是任何非负整数。

如果设置值为“0”表示`no timeout`没有超时。

注意：与web3j进行交易不需要这样做。

### 更多的信息

有关web3j的更多信息，请参阅[web3j主页中文版](http://blog.hubwiz.com/2018/07/10/web3j-index/)。

 

分享一些以太坊、EOS、比特币等区块链相关的交互式在线编程实战教程：

 

> - [java以太坊开发教程](http://xc.hubwiz.com/course/5b2b6e82c02e6b6a59171de2?affid=1125iteye)，主要是针对java和android程序员进行区块链以太坊开发的web3j详解。
> - [java比特币开发教程](http://xc.hubwiz.com/course/5bb35c90c02e6b6a59171df0?affid=1125iteye)，本课程面向初学者，内容即涵盖比特币的核心概念，例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等，同时也详细讲解如何在Java代码中集成比特币支持功能，例如创建地址、管理钱包、构造裸交易等，是Java工程师不可多得的比特币开发学习课程。

 

 

这里是原文[如何在Spring Boot中开始web3j开发](https://github.com/web3j/web3j-spring-boot-starter)