I have a scheduled task that aggregates data every night. The task runs whenever I start up the application and I would like to stop it from running when I run jUnit tests on the applicaton.
@Scheduled(cron = "0 0 0 1 * ?")
public void SalesDataAggregation() {
//aggregation
}
Edit
The method above is also being called here
@PostConstruct
public void init(){
SalesDataAggregation();
}
The method SalesDataAggregate is running on startup because of the @PostConstruct annotation. If you want to keep it from running during tests you can create the class containing the post construct in your test folder and add the @primary annotation so it takes precedence over the class in your main project.
@Primary
public class ClassContainingPostConstruct{
}
You could re-write the PostConstruct
containing bean to an EventListener
(https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2) to trigger on start-up, which I assume is what the purpose of this could be. That bean could then be tied to certain Profile
to only trigger on a specificly enabled profile.
Another option would be to use a property to conditionally trigger it.
public class PostConstructBean {
public boolean isPostConstructEnabled;
public PostConstructBean(@Value("${postconstructenabled}" String value){
isPostConstructEnabled = Boolean.parseBoolean(value);
}
@PostConstruct
public void init(){
if(isPostConstructEnabled){
SalesDataAggregation();
}else{
//NOOP
}
}
}
then just add the property to your environmental properties/overall property file. This has added benefit of allowing you to easier loading/disabling of the bean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With