|
| 1 | +package urjc.gamelink; |
| 2 | + |
| 3 | +import java.net.URI; |
| 4 | +import java.net.URISyntaxException; |
| 5 | + |
| 6 | +import javax.sql.DataSource; |
| 7 | + |
| 8 | +import org.slf4j.Logger; |
| 9 | +import org.slf4j.LoggerFactory; |
| 10 | +import org.springframework.beans.factory.annotation.Value; |
| 11 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
| 12 | +import org.springframework.context.annotation.Bean; |
| 13 | +import org.springframework.context.annotation.Configuration; |
| 14 | + |
| 15 | +import com.zaxxer.hikari.HikariConfig; |
| 16 | +import com.zaxxer.hikari.HikariDataSource; |
| 17 | + |
| 18 | +@Configuration |
| 19 | +public class DatabaseConfig { |
| 20 | + |
| 21 | + private static Logger log = LoggerFactory.getLogger(DatabaseConfig.class); |
| 22 | + |
| 23 | + @Value("${DATABASE_URL:null}") |
| 24 | + private String databaseUrl; |
| 25 | + |
| 26 | + @Bean |
| 27 | + @ConditionalOnProperty("DATABASE_URL") |
| 28 | + public DataSource dataSource() throws URISyntaxException { |
| 29 | + |
| 30 | + log.info("Using database configured in DATABASE_URL=", databaseUrl); |
| 31 | + |
| 32 | + HikariConfig config = new HikariConfig(); |
| 33 | + |
| 34 | + URI uri = new URI(databaseUrl); |
| 35 | + |
| 36 | + String url = "jdbc:" + new URI("postgresql", null, uri.getHost(), uri.getPort(), uri.getPath(), |
| 37 | + uri.getQuery(), uri.getFragment()).toString(); |
| 38 | + |
| 39 | + String[] userInfoParts = uri.getUserInfo().split(":"); |
| 40 | + |
| 41 | + String username = userInfoParts[0]; |
| 42 | + String password = userInfoParts[1]; |
| 43 | + |
| 44 | + config.setJdbcUrl(url); |
| 45 | + config.setUsername(username); |
| 46 | + config.setPassword(password); |
| 47 | + config.setAutoCommit(false); |
| 48 | + |
| 49 | + return new HikariDataSource(config); |
| 50 | + } |
| 51 | +} |
0 commit comments