Search code examples
spring-bootdatasourcehikaricp

Why do i get a null DataSource when running this code using HikariCP?


I'm running this code to set my config and get a DataSource to access a database but when i call ds.getDataSource() i get a null value. What am i missing there?

    private static HikariConfig config = new HikariConfig();
    private static HikariDataSource ds;

    static {
        config.setJdbcUrl("jdbc:mysql://localhost:5656/...");
        config.setUsername("");
        config.setPassword("");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.setMaximumPoolSize(10);
        config.setConnectionTimeout(30000);
        config.setIdleTimeout(600000);
        config.setMaxLifetime(1800000);
        ds = new HikariDataSource(config);
    }

    public static DataSource getDataSource() {
        return ds.getDataSource();
    }

Solution

  • Ok so i wasn't familiar with this aspect of SpringBoot, for anyone having the same problem here is what i did to make the @Autowired work:

    I need to use the DataSource in my a QuickSearchService class which i defined as a @Service. In that service i can call the HikariCP DataSource with @Autowired:

    @Service
    public class QuickSearchService{
    
    @Autowired
    private DataSource ds;
    
    ...
        
    }
    

    Then when i needed to use the service i @Autowired it aswell on call:

    public class UsingService {
    
    @Autowired
    private QuickSearchService qss;
    
    ...
    
    }
    

    Finaly i had to use @ComponentScan on the application main class to tell the server to find the components that need to be autowired:

    @ComponentScan(basePackages = {"example.services", ...})
    public class DemoApplication {
    
    public static void main(String[] args){
    ...
    }
    
    }
    

    Then i can configure the DataSource in the application.properties.