将ConversionService注入自定义Converter

使用Spring MVC-3。我正在编写一个自定义Converter,它需要访问注册到ConversionService的其他Converter。

我该怎么做?我尝试将自定义转换器编写为:

  class CustomConverter<X, Y>{

@Autowired ConversionService service;

//+getter & setters of service

public Y convert(X input){

// I need access to service to lookup simple conversions such as

// String array to Long array etc..

}

}

我通过applicationContext.xml注册了自定义转换器

  <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">

<property name = "converters">

<list>

<bean class="CustomConverter"/>

</list>

</property>

</bean>

但是,spring拒绝将服务注入到我的CustomConverter中(它始终为null)。我该怎么做?

谢谢!

回答:

我最近使用类似的东西来解决这个问题。使用自定义工厂:

public class MyConversionServiceFactoryBean extends ConversionServiceFactoryBean {

@Override

public void afterPropertiesSet() {

super.afterPropertiesSet();

ConversionService conversionService = getObject();

ConverterRegistry registry = (ConverterRegistry) conversionService;

// register converters that need a nested conversion service

registry.addConverter(new MyCustomConverter(conversionService));

}

}

声明如下:

<bean id="conversionService"

class="com.company.MyConversionServiceFactoryBean">

<property name="converters">

<list>

... declare standard converters here ...

</list>

</property>

</bean>

以上是 将ConversionService注入自定义Converter 的全部内容, 来源链接: utcz.com/qa/429787.html

回到顶部