Java Spring Boot CommandLineRunner应用程序中的类型转换
我一直很高兴地使用Java Spring Boot CommandLineRunner应用程序中的类型转换,java,spring,spring-boot,Java,Spring,Spring Boot,我一直很高兴地使用@Value将命令行参数注入到基于Spring Boot CommandLineRunner的程序中。i、 e java -jar myJar.jar --someParm=foo 。。。适用于包含以下内容的类: @Autowired public MyBean(@Value("someParm") String someParm) { ... } 然而,当parm不是一个字符串时,我现在看到它失败了 这是我的豆子: @Component class MyBean {
@Value
将命令行参数注入到基于Spring Boot CommandLineRunner的程序中。i、 e
java -jar myJar.jar --someParm=foo
。。。适用于包含以下内容的类:
@Autowired
public MyBean(@Value("someParm") String someParm) { ... }
然而,当parm不是一个字符串时,我现在看到它失败了
这是我的豆子:
@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)
虽然文档中声明有一个标准的字符串->日期转换器,但我已经尝试注册了自己的转换器,并遇到了与本文相同的NullPointerException:
我能做些什么来让它工作
Java 8,Spring Boot 1.3.5-RELEASE您是否尝试使用
Java.util.Date
而不是Java.time.LocalDate
?我怀疑转换会自动工作。通常(当使用@EnableWebMvc
或类似的东西时)Spring会自动注册转换服务,但在某些情况下(如命令行应用程序),您应该手动注册它:
@Bean
public static ConversionService conversionService() {
return new DefaultFormattingConversionService();
}
我确实试过了——除了类型之外,还有同样的例外。