簡體   English   中英

帶有環境變量的 Spring Boot 配置

[英]Spring boot configuration with environment variables

我有一個 Spring Boot 應用程序,它與 DB 交互以使用 Spring data Rest 提供資源。 我想從環境變量中獲取配置。 下面是我的屬性文件。

spring.datasource.url=${mysql.url}
spring.datasource.username=${mysql.user}
spring.datasource.password=${mysql.password}

我的環境變量在圖像中https://ibb.co/cyxsNc

我什至也嘗試過下面的配置

spring.datasource.url=${MySQL_Url}
spring.datasource.username=${MySQL_User}
spring.datasource.password=${MySQL_Password}

但我無法連接到數據庫並收到以下錯誤

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'

應用文件夾結構

Project
|-- src/main/java
    |-- com.example.app
        |-- DemoApplication.java
|-- src/main/resources
    |-- application.properties

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

spring.datasource.url=jdbc:mysql://localhost:3306/ex_man
spring.datasource.username=root
spring.datasource.password=root

我錯過了什么?

在此處查看此文檔: 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;

import java.util.Map;      // Import this for systemEnvironment

@SpringBootApplication
public class EnvironmentVarsApplication {

    @Value("#{systemEnvironment['ENV_VAR'] ?: 'Default_value'}")
    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);
    }
}

這將打印出環境變量ENV_VAR的值,如果該值不存在,它將打印Default_Value

@Value注入整個項目中可訪問的值。

您可以使用DataSource配置文件並使用System.getEnv("ENV_VARIABLE")方法獲取環境變量。

首先,您應該刪除以“spring.datasource”開頭的屬性。 在 application.properties 中。 然后包含這個准備好的配置文件:

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";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM