如何将bash脚本中的变量传入Java 1.8应用并用于SQL插入操作
解决方案
要把shell脚本中获取的dateLaunch参数传递给Java应用,常用3种可行方案,按推荐优先级排序:
方案1:通过Java系统属性传递(最推荐,实现简单性能高)
- 第一步:修正
setDate.sh脚本,你当前的dateLaunch='$1'写法有问题,单引号不会解析变量,会导致dateLaunch存储的是字面量$1而非实际传入的日期值,修改为双引号,同时在启动Java进程时通过-D参数传入系统属性:
#!/usr/bin/env bash dateLaunch="$1" # 启动Java进程的命令增加系统属性配置 java -Dlaunch.date=${dateLaunch} -jar 你的Java应用包名.jar
- 第二步:Java代码中通过
System.getProperty读取该属性即可,修改后的代码如下:
@Autowired private Service service; @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { try { String formDate = System.getProperty("launch.date"); // 可选:增加参数格式校验,避免非法值入库 if (formDate == null || !formDate.matches("\\d{12}")) { throw new IllegalArgumentException("启动日期参数非法,值为:" + formDate); } service.insertIntoDateTable(formDate); return RepeatStatus.FINISHED; } catch(Exception e) { log.error("Error xyz", e); throw e; } }
该方案完全兼容Java 1.8版本,无需额外依赖。
方案2:通过Spring Batch作业参数传递(适配你当前的技术栈)
从你贴的代码可以判断你使用的是Spring Batch框架,可直接将日期作为作业参数传入:
- shell脚本中启动Spring Batch作业时增加作业参数
launchDate=${dateLaunch} - Java代码中通过注解直接注入参数:
@Value("#{jobParameters['launchDate']}") private String launchDate; @Autowired private Service service; @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { try { service.insertIntoDateTable(launchDate); return RepeatStatus.FINISHED; } catch(Exception e) { log.error("Error xyz", e); throw e; } }
方案3:通过临时文件传递(适合无法修改Java启动命令的场景)
- shell脚本中把日期写入临时文件:
#!/usr/bin/env bash dateLaunch="$1" echo ${dateLaunch} > /var/tmp/launch_date.tmp
- Java代码中读取该临时文件的内容即可,注意提前处理文件不存在、权限不足等异常。
内容的提问来源于stack exchange,提问作者Layla Lawliet
相关产品推荐
相关产品推荐

