此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Vault 3.1.2! |
开始
Spring Vault 支持需要 Vault 0.6 或更高版本以及 Java SE 6 或更高版本。 引导设置工作环境的一种简单方法是在 STS 中创建一个基于 Spring 的项目。
首先,您需要设置一个正在运行的 Vault 服务器。 有关如何启动 Vault 实例的说明,请参阅 Vault。
要在 STS 中创建 Spring 项目,请转到 File → New →
Spring 模板项目 → 简单的 Spring Utility Project →
出现提示时按 Yes。
然后输入项目和包名称,例如org.spring.vault.example
.
然后将以下内容添加到pom.xml
dependencies 部分。
<dependencies>
<!-- other dependency elements omitted -->
<dependency>
<groupId>org.springframework.vault</groupId>
<artifactId>spring-vault-core</artifactId>
<version>3.2.0-SNAPSHOT</version>
</dependency>
</dependencies>
如果你正在使用里程碑或候选版本,你还需要将 Spring Milestone 存储库的位置添加到你的 maven 中pom.xml
该级别与您的<dependencies/>
元素。
<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
存储库也可以在此处浏览。
如果您使用的是 SNAPSHOT,则还需要将 Spring Snapshot 存储库的位置添加到您的 maven 中pom.xml
该级别与您的<dependencies/>
元素。
<repositories>
<repository>
<id>spring-snapshot</id>
<name>Spring Maven SNAPSHOT Repository</name>
<url>https://repo.spring.io/snapshot</url>
</repository>
</repositories>
存储库也可以在此处浏览。
创建一个简单的Secrets
类来保留:
package org.spring.vault.example;
public class Secrets {
String username;
String password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
以及要运行的主应用程序
package org.springframework.vault.example;
import org.springframework.vault.authentication.TokenAuthentication;
import org.springframework.vault.client.VaultEndpoint;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.vault.support.VaultResponseSupport;
public class VaultApp {
public static void main(String[] args) {
VaultTemplate vaultTemplate = new VaultTemplate(new VaultEndpoint(),
new TokenAuthentication("00000000-0000-0000-0000-000000000000"));
Secrets secrets = new Secrets();
secrets.username = "hello";
secrets.password = "world";
vaultTemplate.write("secret/myapp", secrets);
VaultResponseSupport<Secrets> response = vaultTemplate.read("secret/myapp", Secrets.class);
System.out.println(response.getData().getUsername());
vaultTemplate.delete("secret/myapp");
}
}
Even in this simple example, there are few things to take notice of
-
You can instantiate the central class of Spring Vault,
VaultTemplate
, using the org.springframework.vault.client.VaultEndpoint
object and the ClientAuthentication
.
You are not required to spin up a Spring Context to use Spring Vault.
-
Vault is expected to be configured with a root token of
00000000-0000-0000-0000-000000000000
to run this application.
-
The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information).
-
Mapping conventions can use field access.
Notice the Secrets
class has only getters.
-
If the constructor argument names match the field names of the stored document, they will be used to instantiate the object.