带有环境变量的Spring启动配置

时间:2018-02-20 19:37:05

标签: spring spring-boot

我有一个Spring引导应用程序,它与DB交互以使用Spring数据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

我错过了什么?

2 个答案:

答案 0 :(得分:4)

请在此处查看此文档: 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启动可以正确获取环境变量,请参阅下面的测试。

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

这将打印出环境变量ENV_VAR

的值

答案 1 :(得分:0)

您可以使用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";
    }
}
相关问题