0

I am trying to configure a Postgres database in spring boot using annotation configuration. I have all the database credentials in a file named database.properties and the configuration file is called DBconfig.java

database.url= jdbc:postgresql://localhost/mydb 
database.driverClassName= com.postgresql.jdbc.Driver
database.username= postgres
database.password= password

The dbConfig file -

@Configuration
@PropertySource("classpath:databaseAccess/database.properties")

public class DBconfig {

  @Value("${username}")
  private String username;

  @Value("${password}")
  private String password;

  @Value("${url}")
  private String url;

  @Bean
  @Qualifier("postgresDB")
  public DataSource dataSource() {
    DataSourceBuilder dataSource = DataSourceBuilder.create();
    dataSource.url(url);
    dataSource.password(password);
    //dataSource.driverClassName(driverClassName);
    dataSource.username(username);
    return dataSource.build();
  }

  @Bean
  @Qualifier("jdbcTemplate")
  public JdbcTemplate jdbcTemplate() {
      return new JdbcTemplate(dataSource());
  }
}

This is my main file

     @SpringBootApplication
     public class GetNotificationsApplication {

        public static void main(String[] args) {

           ApplicationContext ctx = new AnnotationConfigApplicationContext(DBconfig.class);
           JdbcTemplate template= ctx.getBean("jdbcTemplate", JdbcTemplate.class);
           template.execute("CREATE TABLE TEST( test VARCHAR(20))");

        }

     }

I keep getting the error Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalArgumentException: URL must start with 'jdbc'

Yogendra Mishra
  • 2,399
  • 2
  • 13
  • 20

1 Answers1

0

Try to change value for url parameter by defining port number for postgres. Assuming that postgres is running on 5432 which is the default port.

Change

jdbc:postgresql://localhost/mydb

To

jdbc:postgresql://localhost:5432/mydb

For port number check Find the host name and port using PSQL commands

UPDATE:

Also change @Value("${username}") to @Value("${database.username}") and other properties too by prefix database.

Alien
  • 15,141
  • 6
  • 37
  • 57