ConversionServiceFactoryBean 不工作

ConversionServiceFactoryBean Does Not Work

我正在使用一个特殊的 CacheConfig 对象,它包含一个字段(使用标准 getter/setter 方法),accessExpirationValue,类型为 java.time.Duration。 (编辑: 实际上,该字段是 Long 类型(秒数),但是 getter 和 setter 是 Duration 类型。)

我正在尝试通过将此值设置为秒数并使用 ConversionServiceFactoryBean 将其连接到 Spring,如下所示:

ApplicationContext.xml中的相关bean:

<bean id="conversionService"
    class="org.springframework.context.support.ConversionServiceFactoryBean" >
  <property name="converters">
    <set>
      <bean
          class="com.tjamesboone.example.config.SecondsToDurationConverter"/>
    </set>
  </property>
</bean>

<bean id="cacheConfig" class="com.tjamesboone.example.cache.CacheConfig" >
  <property name="accessExpirationValue" value="0" />
</bean>

SecondsToDurationConverter:

package com.tjamesboone.example.cache;

import java.time.Duration;

import org.springframework.core.convert.converter.Converter;

public class SecondsToDurationConverter implements Converter<String, Duration> {

  @Override
  public Duration convert(String seconds) {
    return Duration.ofSeconds(Long.parseLong(seconds));
  }

}

现在,据我了解,这应该正常工作。当我为 accessExpirationValue 的值传入“0”时,我已经声明了一个处理将字符串转换为 Durations 的 conversionService bean,这意味着应该将值设置为零长度的 Duration。

但这太容易了。它是。因为当我测试我的应用程序时(使用 SpringJUnit4ClassRunner),我得到这个错误,就好像我从未注册过转换器 :

Bean property 'accessExpirationValue' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

所以我的问题是,我做错了什么?我怎样才能让这个按照我想要的方式工作?

作为参考,这是我一直在使用的主要文档: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#core-convert-Spring-config

它具体说,

In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework.

编辑: 我可能还 post CacheConfig 的相关部分!

package com.tjamesboone.example.config;

import java.time.Duration;

public class CacheConfig {

  private Long accessExpirationValue;

  public Duration getAccessExpiration() {
    return Duration.ofSeconds(accessExpirationValue.intValue);
  }

  public void setAccessExpiration() {
    this.accessExpirationValue = expirationDuration.getSeconds();
  }
}

Spring 将尝试将 bean 中的属性与 class 中指定的 getter 和 setter 相匹配。

您的 getters/setters 当前是 getAccessExpiration() 但应该是 getAccessExpirationValue() 以匹配您的 bean 属性 name="accessExpirationValue"。换一个或另一个,你应该有它。