Best practice for dev-only Spring beans

137 Views Asked by At

I am developing a Spring boot application which is built with gradle. There are some beans which should only be part of the application context at development time, let's say some mocks. I understand that Spring profiles can help here.

However, the dev-only classes would still be part of the build and would be rolled out to production and there is a risk that these beans get active by accident.

What is the best way to

  1. have dev-only beans and
  2. exclude them from production build?

The solution should work out of the box, thus without setting up additional packages in the dev classpath in the IDE. I would also like to avoid excluding the classes in the gradle build script because this seems also error-prone.

2

There are 2 best solutions below

0
On

If this is related to dev and not test the only other option besides @Profile("dev") that I see is using @ConditionalOnProperty annotation for your bean with a property defined in application-dev.properties.

This can be done in conjunction with Spring Docs Configuration Properties to facilitate a failure at startup if there is a mismatch in the Configuration. Java Bean Validation can be used as well. Still the classes would be part of your compiled build.

If you want to achieve the second point I would externalize those mocks for example via MockServer or Localstack if applicable. This would avoid having test/mock configurations in your production build.

1
On

Putting test only sources in src/test/java is a standard practice in Maven and Gradle. Those are completely separated from the normal project sources and only used for testing at build time.

If the classes are in libraries you should define those dependencies as test dependencies.