Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manually configure a JdbcTemplate in Spring Boot?

Tags:

java

spring

Here's my basic DAO implementation class:

@Repository
public class MeetingDaoImpl implements MeetingDao {

  @Autowired
  JdbcTemplate jdbcTemplate;

  public boolean insertNewMeeting(String initials, String meetingId, int numYears) {

    int numRowsAffected = jdbcTemplate.update(SQLConstants.INSERT_NEW_MEETING,
        new Object[] {initials.toLowerCase(), meetingId, numYears});

    return numRowsAffected > 0;

  }
}

The jdbcTemplate automatically reads the spring.datasource properties from my application.properties file, which is great, but it includes my DB password which is something I don't want to commit. Instead, I'd like to read it from a local server.properties file instead which I can easily read from a Java class.

Is there a way to configure the jdbcTemplate with Java? I've seen multiple examples using a bean and XML, but none with Java.

like image 679
nicholas79171 Avatar asked Jul 07 '17 12:07

nicholas79171


1 Answers

Just declare a JdbcTemplate bean:

@Bean
JdbcTemplate jdbcTemplate() throws IllegalAccessException, InvocationTargetException, InstantiationException {
    // extract this 4 parameters using your own logic
    final String driverClassName = "org.h2.Driver";
    final String jdbcUrl = "jdbc:h2:mem:test";
    final String username = "sa";
    final String password = "";
    // Build dataSource manually:
    final Class<?> driverClass = ClassUtils.resolveClassName(driverClassName, this.getClass().getClassLoader());
    final Driver driver = (Driver) ClassUtils.getConstructorIfAvailable(driverClass).newInstance();
    final DataSource dataSource = new SimpleDriverDataSource(driver, jdbcUrl, username, password);
    // or using DataSourceBuilder:
    final DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(jdbcUrl).username(username).password(password).build();
    // and make the jdbcTemplate
    return new JdbcTemplate(dataSource);
}

Another way is not to setup datasource parameters in your application.properties file, but to declare it on runtime instead. When you're running your app you can override any properties defined within application.properties or define a new ones.

For example:

java -jar my-spring-boot-app.jar --spring.datasource.url=jdbc:h2:mem:test --spring.datasource.username=sa --spring.datasource.password=secret

The more sophisticated way is to use spring-cloud-config-server or Consul for managing your settings.

like image 124
Bohdan Levchenko Avatar answered Sep 29 '22 07:09

Bohdan Levchenko