0
votes

I am developing a REST API with spring boot v2.0.0.RELEASE coupled with mongoDB. To connect MongoDB im using spring-boot-starter-data-mongodb.

In application.properties I am able to change the basic configurations related to mongodb but my question is what should be the best way to manage these configurations when it comes to advance properties. for example, connections per host property cannot be changed via application.properties.

Therefore I used AbstractMongoConfiguration and extended that in order to provide above mentioned configs such as connections per host. Is that the correct way to do it?

1

1 Answers

1
votes

I used to create external properties files, which can be added as many as possible. I read the properties into a Map<Key, properties> for each properties file.

@PostConstruct
public void properties() throws Exception{
    // read properties and put them into map
    crmPropertiesMap.put(key, properties);
}

@Bean(name = "crmPropertiesMap")
public Map<String, CRMProperties> getCrmPropertiesMap() {

    return crmPropertiesMap;
}

And create new DataSource for each properties file then put them into another map Map<Key, DataSource>.

@Bean
public Map<String, DataSource> dataSourceMap() {

Map<String, DataSource> dataSourceMap = new HashMap<>();

for( CRMProperties crmProperties : crmPropertiesMap.values())
{
    // create DataSource
    dataSourceMap.put(crmProperties.getHotelName(),
                    DataSourceBuilder.create()
                            .url(crmProperties.getSpringDatasourcePrimaryUrl())
                            .driverClassName(crmProperties.getSpringDatasourcePrimaryDriverClassName())
                            .username(crmProperties.getSpringDatasourcePrimaryUsername())
                            .password(crmProperties.getSpringDatasourcePrimaryPassword())
                            .build());

Then create SqlSession

private SqlSession createSqlSession(String id) {

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment(id, transactionFactory, dataSourceMap.get(id));
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(SaleInfoMapper.class);

        return new SqlSessionTemplate(sqlSessionFactoryBuilder.build(configuration));
    }

    @Bean
    public Map<String, SqlSession> sqlSessionMap() {

        Map<String, SqlSession> sqlSessionMap = new HashMap<>();

        for ( String id : dataSourceMap.keySet() )
        {
            sqlSessionMap.put(id, createSqlSession(id));
        }

        return sqlSessionMap;
    }

Then get SqlSession dynamically.

SqlSession sqlSession = sqlSessionMap.get(key);

Hope this helps you.