春季启动cron表达式调度,调用onApplicationEvent的ApplicationListener
问题描述:
我已经写了一个StartupListener通过实现ApplicationListener并重写方法:onApplicationEvent(ContextRefreshedEvent event)。春季启动cron表达式调度,调用onApplicationEvent的ApplicationListener
@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;
}
}
}
在这个方法里面,我试图根据对应于文件的布尔值是否为true来创建一些文件。
使用@Value批注从“application.properties”文件中读取此布尔值。
这StartupListener工作正常。
现在我希望通过安排他们产生这些文件,所以我加了@EnableScheduling到我的主类文件,并创建了一个方法,一个新的Java文件:
@Component
public class FileGenerationScheduler {
@Autowired
StartupListener startupListener;
@Scheduled(cron = "${file.gen.cron}")
public void generateFileWithCron() {
startupListener.onApplicationEvent(null); //passing null here
}
}
此方法被调用指定的cron表达式,但不从“application.properties”中读取所有@Value布尔值。因此默认情况下,这些值将为假(实例变量)
@Value("${create.file.some.merchant}")
private boolean createMerchantAFile;
这存在于StartupListener中,现在为false。所以没有创建。
即使通过调度程序调用,我如何确保这些值是从application.prop中读取的?
答
创建一个服务并添加其中的所有逻辑,包括从属性查找中获取值。将该bean注入侦听器和调度程序类中。