gpt4 book ai didi

java - Spring通过注解在字段中注入(inject)java.util.Date

转载 作者:行者123 更新时间:2023-11-30 02:24:24 24 4
gpt4 key购买 nike

我学习了 Spring 框架并尝试在 fiel 类中注入(inject) 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;
}
}

主类

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>

异常(exception):

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

最佳答案

在 Spring 表达式语言中,#{T(java.util.Date)} 表示对 Date.class 的引用,它与中的 Date 引用不兼容你的 bean 。

如果您想设置诸如系统当前日期之类的内容,您可以尝试

@Value("#{new java.util.Date()}")

甚至是特定日期

@Value("#{new java.text.SimpleDateFormat(\"MM/dd/yyyy\").parse(\"01/01/2018\")}") 

关于java - Spring通过注解在字段中注入(inject)java.util.Date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com