具有环境变量的Spring Boot配置

Sp *_*sha 5 spring spring-boot

我有一个Spring Boot应用程序,它与DB交互以使用Spring Data Rest提供资源。我想从环境变量中获取配置。以下是我的属性文件。

spring.datasource.url=${mysql.url}
spring.datasource.username=${mysql.user}
spring.datasource.password=${mysql.password}
Run Code Online (Sandbox Code Playgroud)

我的环境变量在图像https://ibb.co/cyxsNc中

我什至尝试了以下配置

spring.datasource.url=${MySQL_Url}
spring.datasource.username=${MySQL_User}
spring.datasource.password=${MySQL_Password}
Run Code Online (Sandbox Code Playgroud)

但是我无法连接到数据库并出现以下错误

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalArgumentException: URL must start with 'jdbc'
Run Code Online (Sandbox Code Playgroud)

应用程序文件夹结构

Project
|-- src/main/java
    |-- com.example.app
        |-- DemoApplication.java
|-- src/main/resources
    |-- application.properties
Run Code Online (Sandbox Code Playgroud)

注意:如果我设置如下值,则配置工作正常

spring.datasource.url=jdbc:mysql://localhost:3306/ex_man
spring.datasource.username=root
spring.datasource.password=root
Run Code Online (Sandbox Code Playgroud)

我想念什么?

Rub*_*les 7

您可以使用DataSource配置文件并使用System.getEnv("ENV_VARIABLE")方法获取环境变量。

首先,您应该删除以“spring.datasource”开头的属性。在应用程序属性中。然后包含这个准备好的配置文件:

import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
class JpaConfig {

    @Bean
    public DataSource getDataSource() {
        return DataSourceBuilder.create()
                .driverClassName("com.mysql.cj.jdbc.Driver")
                .url(getDataSourceUrl())
                .username(System.getenv("DB_USERNAME"))
                .password(System.getenv("DB_PASSWORD"))
                .build();
    }

    private String getDataSourceUrl() {
        return "jdbc:mysql://"
                + System.getenv("DB_HOST") + "/"
                + System.getenv("DB_NAME")
                + "?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false";
    }
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*eve 5

在此处查看此文档:https : //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

尝试命名您的环境变量:

SPRING_DATASOURCE_URL

SPRING_DATASOURCE_USERNAME

SPRING_DATASOURCE_PASSWORD

更新:

Spring Boot确实可以正确拾取环境变量,请参见下面的测试。

package com.example.environment_vars;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class EnvironmentVarsApplication {

    @Value("${env.var}")
    private String envVar;

    @Bean
    public CommandLineRunner commandLineRunner() {
        return new CommandLineRunner() {
            @Override
            public void run(String[] arg0) throws Exception {
                System.out.println(envVar);
            }
        };
    }

    public static void main(String[] args) {
        SpringApplication.run(EnvironmentVarsApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将打印出环境变量ENV_VAR的值

  • @AleksandrErokhin您可以在这里找到转换文档:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-relaxed-从环境变量绑定 (2认同)