Krazim00da
Krazim00da

Reputation: 403

What to do if I don't want to set the datasource in application.properties?

I have a spring boot application. And there is a postgres driver. But I don't want to set

spring.datasource.url=jdbc:postgresql://localhost:5432/app

spring.datasource.username=postgres
spring.datasource.password=qwerty

in application.properties, because I did it later in code.

If I delete this part I have problem:

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine suitable jdbc url

How to fix it?

UPD:

    @RequestMapping(value = "setdb/{url}/{db}/{schema}/{login}/{password}")
    public String setDB(@PathVariable(name = "url") String url,
                        @PathVariable(name = "db") String db,
                        @PathVariable(name = "schema") String schema,
                        @PathVariable(name = "login") String login,
                        @PathVariable(name = "password") String password) throws SQLException, ClassNotFoundException {

        this.url = url;
        this.db = db;
        this.schema = schema;
        this.login = login;
        this.password = password;

        Class.forName("org.postgresql.Driver");

        url = "jdbc:postgresql://" + url + "/" + db + "?currentSchema=" + schema + "/";
        connection = DriverManager.getConnection(url, login, password);
//anothercode
}

Upvotes: 2

Views: 869

Answers (2)

Vadym
Vadym

Reputation: 163

You have to define it at .properties file and then use it as source at java class, because it is a best practice to define properties at separate files. As an example I use database properties in my Hibernate config class by annotation @PropertySource(value = "classpath:db.properties")

Upvotes: 1

Beppe C
Beppe C

Reputation: 13973

Spring Boot auto configures the datasource: if you dont want that because you want to take care of it yourself or for other reasons (for example I disable it during unit testing) you can use an annotation

@SpringBootApplication(exclude = {
  DataSourceAutoConfiguration.class
})

Upvotes: 1

Related Questions