0

我有自定义转换器:

public class DateTimeConverter implements Converter<String, DateTime> {

    private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    private DateTimeFormatter formatter;

    private String datePattern = DEFAULT_DATE_PATTERN;

    public String getDatePattern() {
        return datePattern;
    }

    @Autowired(required = false)
    public void setDatePattern(String datePattern) {
        this.datePattern = datePattern;
    }

    @PostConstruct
    public void init() {
        formatter = DateTimeFormat.forPattern(datePattern);
    }

    @Override
    public DateTime convert(String source) {
        if (source == null) return new DateTime();
        return formatter.parseDateTime(source);
    }
}

JavaBean 中的字段:

@NotNull
@Column(name = "dateandtime")
private DateTime dateAndTime;

我在设置中注册了我的转换器:

<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.myapp.util.DateTimeConverter"/>
        </list>
    </property>
</bean>

我得到了这个例外:

Failed to convert property value of type 'java.lang.String' to required type 'org.joda.time.DateTime' for property 'dateAndTime'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.joda.time.DateTime] for property 'dateAndTime': no matching editors or conversion strategy found

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/resources/spring/business-config.xml")
public class JdbcTransactionRepositoryImplTest extends TestCase {

private static final Logger logger = Logger.getLogger(JdbcTransactionRepositoryImplTest.class);

@Autowired
private ApplicationContext context;

private JdbcTransactionRepositoryImpl transactionRepository;

@Before
public void setup() {
    transactionRepository = new JdbcTransactionRepositoryImpl((DataSource)         context.getBean("dataSource"));
}

@Test
public void testFindById() throws Exception {
    Transaction tr1 = transactionRepository.findById(1);
    assertEquals(new Long(1L), tr1.getId());
}

但是,在这种情况下:

@Test
public void testFindById() throws Exception {
    ConversionService conversionService = (ConversionService) context.getBean("conversionService");
    assertTrue(conversionService.canConvert(String.class, DateTime.class));

建立成功!

我不明白:为什么?
感谢您的任何帮助

4

1 回答 1

2

您不必创建自己的转换器或注册转换服务 - 如果 Joda-Time 在项目的类路径中, Spring 将通过注释自动启用转换(必需)。@DateTimeFormat<mvc:annotation-driven />

所以你需要的只是:

@NotNull
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private DateTime dateAndTime;
于 2013-06-19T10:39:42.963 回答