I have written a StartupListener by implementing ApplicationListener and overriding the method: onApplicationEvent(ContextRefreshedEvent event).
@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
private static Logger logger = LoggerFactory.getLogger(StartupListener.class);
@Value("${create.file.some.merchant}")
private boolean createMerchantAFile;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
logger.info("Application context started");
if (createMerchantAFile) {
EmbeddedResponse emb = null;
file = ReportConstants.MERCHANT_A+ ReportConstants.FILE_FORMAT;
try {
emb = genericServices.readJsonFile("merA.json");
generateReport.generateExcelFile(emb, file, "MerchantA");
} catch (IOException ioe) {
logger.error("IO Exception while reading JSON file. Message: ", ioe);
} catch (Exception e) {
logger.error("Exception while reading JSON file. Message", e);
}
createMerchantAFile= false;
}
}
}
Inside this method, I am trying to create some files based on whether a boolean value corresponding to file is true or not.
This boolean value is being read from "application.properties" file by using @Value annotation.
This StartupListener works fine.
Now I wish to generate these files by scheduling them, so I added @EnableScheduling to my main class file, and created a new java file with a method:
@Component
public class FileGenerationScheduler {
@Autowired
StartupListener startupListener;
@Scheduled(cron = "${file.gen.cron}")
public void generateFileWithCron() {
startupListener.onApplicationEvent(null); //passing null here
}
}
This method gets called on the specified cron expression but all the @Value boolean values are not read from "application.properties". So by default these values will be false (instance variables)
@Value("${create.file.some.merchant}")
private boolean createMerchantAFile;
This is present in StartupListener and is now false. So nothing is created.
How can I make sure that these values are read from application.prop even when called via scheduler ?
Create a service and add all the logic in it including the fetching of the value from the property find . Inject that bean inside the listener and the scheduler class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.