1
+ package com .youdemy ;
2
+
3
+ import com .zaxxer .hikari .HikariConfig ;
4
+ import com .zaxxer .hikari .HikariDataSource ;
5
+ import org .slf4j .Logger ;
6
+ import org .slf4j .LoggerFactory ;
7
+ import org .springframework .beans .factory .annotation .Value ;
8
+ import org .springframework .boot .autoconfigure .condition .ConditionalOnProperty ;
9
+ import org .springframework .context .annotation .Bean ;
10
+ import org .springframework .context .annotation .Configuration ;
11
+
12
+ import javax .sql .DataSource ;
13
+ import java .net .URI ;
14
+ import java .net .URISyntaxException ;
15
+
16
+ @ Configuration
17
+ public class DatabaseConfig {
18
+ private static Logger log = LoggerFactory .getLogger (DatabaseConfig .class );
19
+ @ Value ("${DATABASE_URL:postgres://iyfppowuslcaqo:661b996dbc1d0774b74d7ff1daa66973d931d1a1225c06d5e97e0c47ca6542e9@ec2-52-73-155-171.compute-1.amazonaws.com:5432/d6rf3u9o1nmqk5}" )
20
+ private String databaseUrl ;
21
+ @ Bean
22
+ @ ConditionalOnProperty ("DATABASE_URL" )
23
+ public DataSource dataSource () throws URISyntaxException {
24
+ log .info ("Using database configured in DATABASE_URL=" , databaseUrl );
25
+ HikariConfig config = new HikariConfig ();
26
+ URI uri = new URI (databaseUrl );
27
+ String url = "jdbc:" + new URI ("postgresql" , null , uri .getHost (), uri .getPort (), uri .getPath (),
28
+ uri .getQuery (), uri .getFragment ()).toString ();
29
+ String [] userInfoParts = uri .getUserInfo ().split (":" );
30
+ String username = userInfoParts [0 ];
31
+ String password = userInfoParts [1 ];
32
+ config .setJdbcUrl (url );
33
+ config .setUsername (username );
34
+ config .setPassword (password );
35
+ config .setAutoCommit (false );
36
+ return new HikariDataSource (config );
37
+ }
38
+ }
0 commit comments