【发布时间】: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