简体   繁体   中英

How to have a datasource configuration as external Jar in spring boot

I want to create a spring boot JAR(standalone) which contains Java data source configuration and I want to utilize that JAR in other micro services for connecting to DB (instead of giving credentials in each application.properties file). I have succeeded in creating the JAR with java data source configuration. But when I add that jar to any service, the service is still expecting me to provide credentials in application.properties.

Could anyone help on how to have data source configuration in an external JAR and use that jar in service for db connection

You could implement a single properties file to take the data source credentials from there (you don't necessarily have to use Spring Boot's default application.properties) and then the easiest way to get the connection is by defining a DataSource factory method and placing it inside a class annotated with the @Configuration annotation:

@Configuration
public class DataSourceConfig {
    
    @Bean
    public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.h2.Driver");
        dataSourceBuilder.url("jdbc:h2:mem:test");
        dataSourceBuilder.username("SA");
        dataSourceBuilder.password("");
        return dataSourceBuilder.build();
    }
}

This manually generates the connection to the data source that you are indicating, just make sure that all the necessary libraries for the connection are being imported correctly in your pom.xml file if you are using Maven.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM