RLeyva
RLeyva

Reputation: 77

Configuring Datasource Properties

I am having trouble setting my datasource properties in my java bean configuration class. It appears that the properties aren't being read in properly from the yaml file. I am getting a null pointer exception when the driver class name is attempted to be accessed.

This is my java bean config file:

@Configuration
public class AppConfig {

    @Autowired
    private DataSourceProperties properties;

    //other beans here

    @Bean
    public DataSource dataSource(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setJdbcUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());

    @Bean
    public DataSourceProperties properties(){
        return new DataSourceProperties();
    }
}

I also tried:

@Configuration
public class AppConfig {

    //other beans here

    @Bean
    public DataSource dataSource(DataSourceProperties properties){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setJdbcUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());

        return dataSource;
    }

    @Bean
    public DataSourceProperties properties(){
        return new DataSourceProperties();
    }

}

I also tried to use springframeowrk.jdbc's DriverManagerDataSource instead of Hikari, but it still wouldn't work.

This is my application.yml file in src/main/resources:

spring:
    datasource:
        driverClassName: 'com.ibm.db2.jcc.DB2Driver'
        username: 'appUsername'
        password: 'appPw'
        url: 'datasourceURL'      

Has anyone had a similar problem to this and would know how to set get the properties set correctly?

Upvotes: 0

Views: 1694

Answers (2)

Anton Bessonov
Anton Bessonov

Reputation: 9803

Example of my config:

spring:
  datasource:
    driverClassName: org.mariadb.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db
    username: user
    password: pass
    connectionInitSql: "SET NAMES 'utf8mb4'" # hikari
    validationQuery: SELECT 1
    type: com.zaxxer.hikari.HikariDataSource

hikari has additional options like connectionInitSql. As already suggested, there is no need for own config.

Upvotes: 1

Florian
Florian

Reputation: 140

You don't need extra Beans when you configure your DataSource in application.yml

Upvotes: 1

Related Questions