Skip to content

Can I choose to include/exclude what controller is deployed per environment in Spring Boot?

I would like to expose an endpoint only to certain TEST environment and leave it out altogether in PROD.

I will have a separate @RestController for this endpoint. My question is how to ensure this endpoint is accessible only from the test env and never in production?

I tried to play around with @ComponentScan, but didn’t get very far.



The best, easiest and safest solution is to use Spring Profiles. Use the annotation @Profile to specify what environment a certain bean should be created on. Note that if the environment doesn’t match the @Profile annotation value, the bean is not created at all so it doesn’t appear in the application container.

Assuming the following files defining the environments you want to hide such REST controller:

  • src/main/resources/application.yml (general configuration)
  • src/main/resources/application-prod.yml (production environment)
  • src/main/resources/application-int.yml (integrationenvironment)

… and these you want to make the REST controller visible for:

  • src/main/resources/application-dev.yml (development environment)
  • src/main/resources/application-local.yml (localhost environment)
  • src/test/resources/application-test.yml (unit/integration tests, note a different folder)

You can configure the REST controller for the lower environments easily. Remember the bean is created if any of the listed profiles (environments) is active, therefore understand it as the or clause.

@Profile({"dev", "local", "test"})
public class MyRestController {
    // implementation
2 People found this is helpful