gpt4 book ai didi

java - 将 ConversionService 注入(inject)自定义转换器

转载 作者:IT老高 更新时间:2023-10-28 13:48:50 27 4
gpt4 key购买 nike

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

我怎样才能做到这一点?我尝试将我的自定义转换器编写为:

  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 拒绝将服务注入(inject)我的 CustomConverter(它始终为空)。我怎样才能做到这一点?

谢谢!

最佳答案

我遇到了同样的问题。有一个issue SPR-6415在 Spring JIRA 中涵盖了这个问题。我已经根据这个问题的讨论在这里给出了我的解决方案。这与@nmervaillie 的回答原理相同,但您不必实现自己的 ConversionServiceFactoryBean

/**
* Base class of @{code Converter} that need to use {@code ConversionService}.
* Instances of implementing classes must be spring-managed to inject ConversionService.
*
* @author Michal Kreuzman
*/
public abstract class CoversionServiceAwareConverter<S, T> implements Converter<S, T> {

@Inject
private ConversionService conversionService;

protected ConversionService conversionService() {
return conversionService;
}

/**
* Add this converter to {@code ConverterRegistry}.
*/
@SuppressWarnings("unused")
@PostConstruct
private void register() {
if (conversionService instanceof ConverterRegistry) {
((ConverterRegistry) conversionService).addConverter(this);
} else {
throw new IllegalStateException("Can't register Converter to ConverterRegistry");
}
}
}

@Component
public class SampleConverter extends CoversionServiceAwareConverter<Object, Object> {

@Override
public String convert(Object source) {
ConversionService conversionService = conversionService();

// Use conversionService and convert
}
}

关于java - 将 ConversionService 注入(inject)自定义转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8336387/

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