I'm developing an app with Spring Boot and I have a configuration class that generates a @Bean DataSource.
I would like to generate alternative connection levels for connecting to the database, such as if the environment variables are incorrect, using data from application.properties, if it is also using configuration class, regardless of this order, would like a similar result, it is possible to configure this way, is there any doc that I can follow?
I believe I have a more dynamic and responsive connection environment in this way.
DataSource Bean Class
package foo.bar.configuration;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class DataBaseConfiguration {
private final static String DATABASE_CONNECTION_ROOT_USERNAME = "foo";
private final static String DATABASE_CONNECTION_ROOT_PASSWORD = "bar";
private final static String DATABASE_CONNECTION_URL = "jdbc:mysql://localhost:3306/foobar";
@Bean
@Primary
public DataSource dataSource() {
final DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(DatabaseDriver.MYSQL.getDriverClassName());
driverManagerDataSource.setUrl(DATABASE_CONNECTION_URL);
driverManagerDataSource.setUsername(DATABASE_CONNECTION_ROOT_USERNAME);
driverManagerDataSource.setPassword(DATABASE_CONNECTION_ROOT_PASSWORD);
return driverManagerDataSource;
}
}