【问题标题】:How to access command line arguments in Spring configuration?如何在 Spring 配置中访问命令行参数?
【发布时间】:2016-04-21 13:08:48
【问题描述】:

我有一个使用 Spring Integration 存储过程入站通道适配器的 Spring Boot 应用程序。我想将命令行参数传递给存储过程。 Spring Boot 文档说 SpringApplication 会将任何以“--”开头的命令行选项参数转换为属性并将其添加到 Spring 环境中。在 int-jdbc:parameter 元素中访问此属性的正确方法是什么?

Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext ctx = new SpringApplication("integration.xml").run(args);
        System.out.println("Hit Enter to terminate");
        System.in.read();
        ctx.close();
    }    
}

集成.xml

<int-jdbc:stored-proc-inbound-channel-adapter
    stored-procedure-name="sp_get_some_records"
    data-source="dataSource"
    channel="recs.in.channel"
    id="recs.in">

    <int:poller fixed-rate="86400" time-unit="SECONDS" />

    <int-jdbc:parameter name="myarg" type="java.lang.Integer" value="${arg1}" />

</int-jdbc:stored-proc-inbound-channel-adapter>

在这里使用${arg1} 似乎没有得到解决。什么是正确的语法,还是我需要定义一个额外的属性或属性占位符?

启动应用程序,例如使用java -jar app.jar --arg1=5 会抛出

的异常
Error converting typed String value for bean property 'value'; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [java.lang.Integer]; nested exception is java.lang.NumberFormatException: For input string: "${arg1}"

我认为首先它与类型转换有关并尝试了

<int-jdbc:parameter name="myarg" type="java.lang.Integer" value="#{ T(java.lang.Integer).parseInt(arg1) }" />

但这也没用。

【问题讨论】:

  • 你在命令行中传递了什么值?
  • 我试过了,例如--arg1=5

标签: java spring spring-boot spring-integration


【解决方案1】:

如果我是你,我会将你的 XML 配置转换为 JavaConfig。然后你可以使用

在你的配置类中访问你的属性
@Value("${arg1}")
private Integer arg1;

【讨论】:

  • 对JavaConfig不熟悉,希望能找到适合我现有xml配置的解决方案。
【解决方案2】:

你没有任何 Spring Boot 的东西。

我的意思是auto-configuration,其中也包括PropertyPlaceholderConfigurer

一定是这样的:

@SpringBootApplication
@ImportResource("integration.xml")
public class Application {
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
        System.out.println("Hit Enter to terminate");
        System.in.read();
        ctx.close();
    }    
}

我刚刚检查了我们的barrier 示例:https://github.com/spring-projects/spring-integration-samples/tree/master/basic/barrier

【讨论】:

  • 抱歉,忘记包含我的 Application.java 的那部分。我更新了我原来的帖子。我在 Application 类之前确实有@SpringBootApplication
  • 没关系,因为你的SpringApplication("integration.xml").run(args) 不知道@Configuration 类。 IT 也必须包含在 source 中:new SpringApplication(Application.class, "integration.xml")
猜你喜欢
  • 2022-01-19
  • 2014-07-24
  • 2013-07-16
  • 1970-01-01
  • 2020-04-28
  • 2018-10-01
  • 1970-01-01
相关资源
最近更新 更多