spring_reference/VI. Deploying to the cloud/49.1. Binding to services.md

24 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 49.1. 绑定服务
默认情况下,运行应用的元数据和服务连接信息被暴露为应用的环境变量(比如,$VCAP_SERVICES。采用这种架构的原因是因为Cloud Foundry多语言特性任何语言和平台都支持作为buildpack。进程级别的环境变量是语言无关language agnostic的。
环境变量并不总是有利于设计最简单的API所以Spring Boot自动提取它们然后将这些数据导入能够通过Spring `Environment`抽象访问的属性里:
```java
@Component
class MyBean implements EnvironmentAware {
private String instanceId;
@Override
public void setEnvironment(Environment environment) {
this.instanceId = environment.getProperty("vcap.application.instance_id");
}
// ...
}
```
所有的Cloud Foundry属性都以vcap作为前缀。你可以使用vcap属性获取应用信息比如应用的公共URL和服务信息比如数据库证书。具体参考VcapApplicationListener Javadoc。
**注**[Spring Cloud Connectors](http://cloud.spring.io/spring-cloud-connectors/)项目很适合比如配置数据源的任务。Spring Boot提供自动配置支持和一个`spring-boot-starter-cloud-connectors` starter POM。