Search code examples
springspring-bootmicroservicesspring-cloudapache-zookeeper

Duplicate config code problem for all spring microservices


Is there a way to create a spring configuration class and use it to all my microservices?

Right now I have to copy a duplicate config class to all microservices. And if there are changes , I have to make them in all modules.

I use the apache zookeeper for centralize my configurations in single place. For setting authentication details on connection to zookeeper server I have to create a new bean for CuratorFramework class in spring @Configuration in any microservices that keep their configs on the zookeeper.


Solution

  • Yes, you can:

    • Create a module with a configuration (maven, gradle managed, whatever). Add all common beans to this module for reuse. It will be a kind of "infra".
    • Optionally add a spring.factories file to automatically "load" the configuration
    • In Microservices (each of them should be in a different module) add a dependency on that common module.

    If you've added spring.factories - the configuration will be loaded automatically, if you didn't you'll have to import this configuration explicitly in each module. But in any case you won't need to duplicate code.

    There are many tutorials / threads in SO about spring factories, so in case you're not familiar with this feature - you can read here for example