You can configure your database credentials either via environment variables (recommended) or directly in application.properties.
# .env.example
# Application name
SPRING_APPLICATION_NAME=spring-boot-project
# Database configuration
DB_URL=jdbc:postgresql://localhost:5432/springbootdb
DB_USERNAME=springuser
DB_PASSWORD=springpasswordPlace this file under src/main/java/com/example/spring_boot_project/config/DotenvInitializer.java:
package com.example.spring_boot_project.config;
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DotenvInitializer {
public static Dotenv dotenv;
@PostConstruct
public static void init(){
try {
dotenv = Dotenv.configure()
.ignoreIfMissing()
.load();
System.out.println("Dotenv loaded");
} catch (DotenvException e) {
throw new RuntimeException(e);
}
}
}This will load the
.envfile and make variables available viaDotenvInitializer.dotenv.
In src/main/java/com/example/spring_boot_project/SpringBootProjectApplication.java:
package com.example.spring_boot_project;
import com.example.spring_boot_project.config.DotenvInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootProjectApplication {
public static void main(String[] args) {
DotenvInitializer.init();
SpringApplication.run(SpringBootProjectApplication.class, args);
}
}String dbUrl = DotenvInitializer.dotenv.get("DB_URL");You can then configure your datasource programmatically or pass these variables to Spring.
Alternatively, configure your database connection directly in src/main/resources/application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/springbootdb
spring.datasource.username=springuser
spring.datasource.password=springpassword
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true