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.
Advertisement
Answer
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 application.properties
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"}) @RestController public class MyRestController { // implementation }