【问题标题】:Type conversion in Spring Boot CommandLineRunner appSpring Boot CommandLineRunner 应用中的类型转换
【发布时间】:2016-10-08 15:03:08
【问题描述】:

我一直很高兴使用@Value 将命令行参数注入基于 Spring Boot CommandLineRunner 的程序中。即

 java -jar myJar.jar --someParm=foo

... 适用于包含以下内容的类:

 @Autowired
 public MyBean(@Value("someParm") String someParm) { ... }

但是,当参数不是字符串时,我现在看到此失败。

这是我的豆子:

@Component
class MyBean {

    private final LocalDate date;

    @Autowired
    public MyBean (@Value("date") @DateTimeFormat(iso=ISO.DATE) LocalDate date) {
        this.date = date;
    }

    public void hello() {
        System.out.println("Hello on " + date);
    }

}

...和我的应用程序类:

@SpringBootApplication
public class MyApp implements CommandLineRunner {

    @Autowired
    private MyBean myBean;

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @Override
    public void run(String... args) throws IOException {
        myBean.hello();
    }
}

当我以java -jar MyApp.java --date=2016-12-10 运行它时,我得到一个堆栈跟踪结束:

 java.lang.IllegalStateException: Cannot convert value of type
 [java.lang.String] to required type [java.time.LocalDate]: 
 no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:302)

虽然文档声明有一个 String->Date 的标准转换器,但我已经尝试注册自己的转换器,并遇到与本文相同的 NullPointerException:How to register custom converters in spring boot?

我可以做些什么来完成这项工作?

Java 8,Spring Boot 1.3.5-发布

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    您是否尝试使用java.util.Date 而不是java.time.LocalDate?我怀疑转换会自动进行。

    【讨论】:

    • 我确实尝试过——除了类型之外,同样的异常。
    【解决方案2】:

    一般情况下(使用@EnableWebMvc之类的)Spring会自动注册转换服务,但也有一些情况(比如命令行应用)需要手动注册:

    @Bean
    public static ConversionService conversionService() {
        return new DefaultFormattingConversionService();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 2019-03-21
      • 2015-02-23
      • 2016-03-04
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2017-07-15
      相关资源
      最近更新 更多