I have a controller annotated with @Scheduled
but when the test environment is active it also runs.
Is it possible to check the environment in which application is running for the method to run only in production?
I have a controller annotated with @Scheduled
but when the test environment is active it also runs.
Is it possible to check the environment in which application is running for the method to run only in production?
If there is any parameter table for the system, you could add the environment information and check if it is production to be able to execute the method. Depending on your scenario this would be a simpler solution.
You can create a variable in a property file for testing, to have its test properties separate from the default (from the file application.properties
)
First, let's create the file in the following format, to create a test profile (% em_profile):
application-tst.properties
Include in this properties file a setting for you to understand which environment you are in:
ambiente = teste
And in the original file tst
, add:
ambiente = producao
So we can distinguish the two environments. You can now run your using this new profile ( application.properties
) application.
mvn spring-boot:run -Drun.profiles=tst
Or:
java -jar -Dspring.profiles.active=tst XXX.jar
Then use the annotation tst
:
@ConditionalOnProperty(name="ambiente", havingValue="producao")
public class Schedule {
@Scheduled
public class algumScheduler() {
// código
}
}
If you prefer, you can use @ConditionalOnProperty
in the method itself too if you wish.