我学习Spring框架并尝试在fiel类中注入java.util.Date
。
让Foo.class
package beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class Foo {
@Value("Hello foo")
private String string;
@Value("#{T(java.util.Date)}")
private Date date;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
Main.class
import beans.Foo;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(ctx.getBean(Foo.class).getString());
System.out.println(ctx.getBean(Foo.class).getDate());
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="beans"/>
</beans>
Exeption:
Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'foo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Date beans.Foo.date; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.Class' to required type 'java.util.Date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.Class] to required type [java.util.Date]: no matching editors or conversion strategy found
答案 0 :(得分:2)
在Spring Expression Language中,#{T(java.util.Date)} 表示对 Date.class 的引用,它与日期引用不兼容你的豆子。
如果您想设置类似系统当前日期的内容,可以尝试
@Value("#{new java.util.Date()}")
甚至是特定日期
@Value("#{new java.text.SimpleDateFormat(\"MM/dd/yyyy\").parse(\"01/01/2018\")}")