0

我的 Spring Boot 应用程序在 PCF 中,因为 PCF 没有在运行时更改属性文件的选项,所以我试图将值放入 PCF VCAP_SERVICES-用户提供的凭据中。

我尝试按照关键提供的教程使用@ConfigurationProperties,但我得到了空异常。

@Data
@Configuration
@ConfigurationProperties("vcap.services.app-properties.credentials")
public class RsTest {
private String username;
private String password;
//getter and setter
};

我的控制器看起来像

@RestController
public class RestApiController {
@Autowired
RsTest rsTest;

public void test() {
logger.info("RSTest: "+rsTest.getUsername());
return ResponseEntity.ok().body("some value");
}

我期待 RsTest 对象中的凭据。但是在路径 [/myservice] 的上下文中,servlet [dispatcherServlet] 的错误 Servlet.service() 引发了异常 2019-08-20T17:32:43.728-04:00 [APP/PROC/WEB/0] [OUT] java。 lang.NullPointerException: null

4

1 回答 1

1

好吧,理论上你所拥有的应该是可行的。但是,从 VCAP_SERVICES 解析配置是一种脆弱的方法,这就是我猜测您遇到问题的原因。for 的前缀@ConfigurationProperties必须完全正确,Spring 才能查找该值,并且前缀将取决于您绑定的服务的名称。

Spring Boot 将以以下格式映射绑定到您的应用程序的服务:vcap.services.<service name>.credentials.<credential-key>. 有关详细信息,请参阅此处的文档

如果您没有正确的服务实例名称,那么它将无法绑定到您的配置属性对象。

这是一个例子:

  1. 我有一个名为scheduler.
  2. 它产生以下 VCAP_SERVICES 环境变量:

    {
      "scheduler-for-pcf": [
       {
        "binding_name": null,
        "credentials": {
         "api_endpoint": "https://scheduler.run.pivotal.io"
        },
        "instance_name": "scheduler",
        "label": "scheduler-for-pcf",
        "name": "scheduler",
        "plan": "standard",
        "provider": null,
        "syslog_drain_url": null,
        "tags": [
         "scheduler"
        ],
        "volume_mounts": []
       }
      ]
     }
    
  3. 我可以使用以下类来读取它的凭据。

    @Configuration
    @ConfigurationProperties(prefix = "vcap.services.scheduler.credentials")
    public class SchedulerConfig {
        private String api_endpoint;
    
        public String getApiEndpoint() {
            return api_endpoint;
        }
    
        public void setApiEndpoint(String api_endpoint) {
            this.api_endpoint = api_endpoint;
        }
    }
    

如果我将服务名称更改为fred,则前缀需要更改为vcap.services.fred.credentials.


说了这么多,您应该考虑改用java-cfenv。它更灵活,并且是在 Java 应用程序中读取 VCAP_SERVICES 的推荐方法(注意 - 这取代了 Spring Cloud 连接器)。

有关更多详细信息,请阅读此博客文章

于 2019-08-22T19:11:37.497 回答