|
| 1 | +package es.codeurjc.wallypop.configuration; |
| 2 | + |
| 3 | +import com.zaxxer.hikari.HikariConfig; |
| 4 | +import com.zaxxer.hikari.HikariDataSource; |
| 5 | +import org.slf4j.LoggerFactory; |
| 6 | +import org.springframework.beans.factory.annotation.Value; |
| 7 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
| 8 | +import org.springframework.context.annotation.Bean; |
| 9 | +import org.springframework.context.annotation.Configuration; |
| 10 | + |
| 11 | +import javax.sql.DataSource; |
| 12 | +import java.net.URI; |
| 13 | +import java.net.URISyntaxException; |
| 14 | +import java.util.logging.Level; |
| 15 | +import java.util.logging.Logger; |
| 16 | + |
| 17 | +@Configuration |
| 18 | +public class DatabaseConfig { |
| 19 | + @Value("${DATABASE_URL:null}") |
| 20 | + private String databaseUrl; |
| 21 | + @Bean |
| 22 | + @ConditionalOnProperty("DATABASE_URL") |
| 23 | + public DataSource dataSource() throws URISyntaxException { |
| 24 | + HikariConfig config = new HikariConfig(); |
| 25 | + URI uri = new URI(databaseUrl); |
| 26 | + String url = "jdbc:" + new URI("postgresql", null, uri.getHost(), uri.getPort(), uri.getPath(), |
| 27 | + uri.getQuery(), uri.getFragment()).toString(); |
| 28 | + String[] userInfoParts = uri.getUserInfo().split(":"); |
| 29 | + String username = userInfoParts[0]; |
| 30 | + String password = userInfoParts[1]; |
| 31 | + config.setJdbcUrl(url); |
| 32 | + config.setUsername(username); |
| 33 | + config.setPassword(password); |
| 34 | + config.setAutoCommit(false); |
| 35 | + return new HikariDataSource(config); |
| 36 | + } |
| 37 | +} |
0 commit comments