DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Get Closer to Consistency in Microservice Architecture
  • How Kafka Can Make Microservice Planet a Better Place
  • Spring Microservice Application Resilience: The Role of @Transactional in Preventing Connection Leaks
  • Scaling Java Microservices to Extreme Performance Using NCache

Trending

  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia
  • Applying Microservices Lessons to Multi-Agent AI Systems
  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Should Developers Switch From SQLite to DuckDB?

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Secure database connection strings in Spring microservices using environment variables and placeholder expressions for the hostname using the properties file.

By 
Amol Gote
DZone Core CORE ·
Jul. 24, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Managing database connection strings securely for any microservice is critical; often, we secure the username and password using the environment variables and never factor in masking or hiding the database hostname. In reader and writer database instances, there would be a mandate in some organizations not to disclose the hostname and pass that through an environment variable at runtime during the application start. This article discusses configuring the hostname through environment variables in the properties file. 

Database Configurations Through Environment Variables

We would typically configure the default connection string for Spring microservices in the below manner, with the database username and password getting passed as the environment variables. 

Java
 
server.port=8081
server.servlet.context-path=/api/e-sign/v1
spring.esign.datasource.jdbc-url=jdbc:mysql://localhost:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false
spring.esign.datasource.username=${DB_USER_NAME}
spring.esign.datasource.password=${DB_USER_PASSWORD}
spring.esign.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.esign.datasource.minimumIdle=5
spring.esign.datasource.maxLifetime=120000


If our microservice connects to a secure database with limited access and the database administrator or the infrastructure team does not want you to provide the database hostname, then we have an issue. Typically, the production database hostname would be something like below:   

Java
 
spring.esign.datasource.jdbc-url=jdbc:mysql://prod-db.fabrikam.com:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false
spring.esign.datasource.username=${DB_USER_NAME}
spring.esign.datasource.password=${DB_USER_PASSWORD}


Using @Configuration Class

In this case, the administrator or the cloud infrastructure team wants them to provide the hostname as an environment variable at runtime when the container starts. One of the options is to build and concatenate the connection string in the configuration class as below: 

Java
 
@Configuration
public class DatabaseConfig {

    private final Environment environment;

    public DatabaseConfig(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public DataSource databaseDataSource() {
        String hostForDatabase = environment.getProperty("ESIGN_DB_HOST", "localhost:3306");
        String dbUserName = environment.getProperty("DB_USER_NAME", "user-name");
        String dbUserPassword = environment.getProperty("DB_USER_PASSWORD", "user-password");
        String url = String.format("jdbc:mysql://%s/e-sign?allowPublicKeyRetrieval=true&useSSL=false", hostForDatabase);

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(dbUserName); // Replace with your actual username
        dataSource.setPassword(dbUserPassword); // Replace with your actual password
        return dataSource;
    }
}


The above approach would work, but we need to use the approach with application.properties, which is easy to use and quite flexible. The properties file allows you to collate all configurations in a centralized manner, making it easier to update and manage. It also improves readability by separating configuration from code. The DevOps team can update the environment variable values without making code changes.

Environment Variable for Database Hostname

Commonly, we use environment variables for database username and password and use the corresponding expression placeholder expressions ${} in the application properties file.

Java
 
spring.esign.datasource.username=${DB_USER_NAME}
spring.esign.datasource.password=${DB_USER_PASSWORD}


However, for the database URL, we need to use the environment variable only for the hostname and not for the connection string, as each connection string for different microservices would have different parameters. So, to address this, Spring allows you to have the placeholder expression within the connection string shown below; this gives flexibility and the ability to stick with the approach of using the application.properties file instead of doing it through the database configuration class. 

Java
 
spring.esign.datasource.jdbc-url=jdbc:mysql://${ESIGN_DB_HOST}:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false


Once we have decided on the above approach and if we need to troubleshoot any issue for whatever reason in lower environments, we can then use the ApplicationListener interface to see the resolved URL:

Java
 
@Component
public class ApplicationReadyLogger implements ApplicationListener<ApplicationReadyEvent> {

    private final Environment environment;

    public ApplicationReadyLogger(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        String jdbcUrl = environment.getProperty("spring.esign.datasource.jdbc-url");
        System.out.println("Resolved JDBC URL: " + jdbcUrl);
    }
}


If there is an issue with the hostname configuration, it will show as an error when the application starts. However, after the application has been started, thanks to the above ApplicationReadyLogger implementation, we can see the database URL in the application logs. Please note that we should not do this in production environments where the infrastructure team wants to maintain secrecy around the database writer hostname.   

Using the above steps, we can configure the database hostname as an environment variable in the connection string inside the application.properties file.

Conclusion

Using environment variables for database hostnames to connect to data-sensitive databases can enhance security and flexibility and give the cloud infrastructure and DevOps teams more power. Using the placeholder expressions ensures that our configuration remains clear and maintainable.

Database Database connection Java (programming language) microservice Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How To Get Closer to Consistency in Microservice Architecture
  • How Kafka Can Make Microservice Planet a Better Place
  • Spring Microservice Application Resilience: The Role of @Transactional in Preventing Connection Leaks
  • Scaling Java Microservices to Extreme Performance Using NCache

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook