我正在尝试将 Spring Boot 应用程序部署到连接 Postgres 支持服务的 CF。我可以看到数据库属性在运行时没有被 VCAP env 替换。 我正在使用依赖项 - spring-boot-starter-jdbc (不是 spring-boot-starter-data-jpa,因为我打算使用 JDBC 模板而不是 JPA)。
步骤
在 pom.xml 中添加了以下 jar(spring-boot-starter-data-jpa、postgresql-driver)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
创建一个返回 DataSource 类型的 bean
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
@SuppressWarnings("rawtypes")
DataSourceBuilder builder = DataSourceBuilder.create();
return builder.build();
}
在 application.properties 中指定连接属性。
spring.datasource.jdbcUrl=jdbc:postgresql://localhost:5432/test
spring.datasource.username= dummy
spring.datasource.password=dummy
spring.datasource.platform=postgresql
这样本地设置就可以正常工作了。当应用程序部署到 Cloud Foundry 时,期望 spring 自动重新配置应该使用 vcap 中的属性替换 bean。
然而,这些值似乎没有被替换,系统尝试连接到 CF 上的本地主机,但失败了。
我已经查看了所有文档,它们似乎可以与 spring-boot-starter-data-jpa 一起使用,但不能与 jdbc 一起使用。我可以看到自动重新配置在 JDBC 场景中不起作用。
感谢任何帮助。
感谢和问候, 维拉
最佳答案
我强烈建议您避免使用自动重新配置。对于演示来说这很酷,但最终很难真正使用。它有点太神奇了,当它不起作用时很难调试,这就是您在这里遇到的情况。
还有其他几种方法可以实现此目的:
- Spring Boot 公开
VCAP_SERVICES
作为类似vcap.services.<name>.credentials.username
的属性。您可以使用它们来手动定义数据源。请参阅here 。将此与“云”配置文件相结合,可以轻松在本地和云之间切换。 - 您可以use Spring Cloud Connectors 。当您使用 SCC 时,自动重新配置将自动停止。然后,您可以使用 SCC 选择一个服务并从中获取数据源。
- 您可以使用新的 java-cfenv库,即 intended to complement Spring Boot better .
关于java - Spring Boot 自动重新配置在 spring-boot-data-starter-jdbc 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571077/