2015-08-15 88 views
0

我想使用Spring自定義轉換器從我的持久對象轉換爲Json對象(用於UI層)。春季轉換器重用

DBO的

class Adbo{ 
    Bdbo b = new Bdbo(); 
} 
class Bdbo{} 

UI POJO。

class APoj{ 
    BPoj b = new Poj(); 
} 
class BPoj{} 

這是我的轉換器

class APojToADbo implements Converter<ADbo, APoj>{ 
    @Override 
    public APoj convert(ADbo source) { 
     //..code to convert 
     //..also includes conversion from BDbo to BPoj 
    } 
} 
class ADboToAPoj implements Converter<APoj, ADbo>{ 
    @Override 
    public ADbo convert(APoj source) { 
     //..code to convert 
     //..also includes conversion from BPoj to BDbo 
    } 
} 
class BPojToBDbo implements Converter<BDbo, BPoj>{ 
    @Override 
    public BPoj convert(BDbo source) { 
     //..code to convert 
    } 
} 
class BDboToBPoj implements Converter<BPoj, BDbo>{ 
    @Override 
    public BDbo convert(BPoj source) { 
     //..code to convert 
    } 
} 

註冊我轉換到ConversionService這個

@Bean 
public ConversionServiceFactoryBean getConversionService(){ 
    ConversionServiceFactoryBean c = new ConversionServiceFactoryBean(); 
    Set<Converter> converters = new HashSet<>(); 
    converters.add(aPojToADbo); 
    converters.add(aDboToAPoj); 
    converters.add(bPojToBDbo); 
    converters.add(bDboToBPoj); 
    c.setConverters(converters); 
    return c; 
} 

現在我試圖重構,這樣我可以避開2個地方寫這篇

//..also includes conversion from BDbo to BPoj 
//..also includes conversion from BPoj to BDbo 

,所以,我沒有這在APojToADbo

@Autowired 
protected ConversionService conversionServ; 

而且如果我做上面的,我得到以下異常

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 

由於國際奧委會未在ConversionService豆尚未完成。循環依賴!

this如何避免循環依賴好文章,但我想知道,如果Spring提供任何清潔劑/優雅的方式來做到這一點內部轉換器

回答

0

我建議你返回ConversionService和設置的afterPropertiesSet

@Bean 
    public ConversionService getConversionService() { 
    ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); 
      bean.setConverters(getConverters()); 

    bean.afterPropertiesSet(); 

    ConversionService object = bean.getObject(); 
    return object; 
      } 
+0

還是一樣的問題 - '致:org.spr ingframework.beans.factory.BeanCurrentlyInCreationException:創建名爲'getConversionService'的bean時出錯:請求的bean當前正在創建:是否存在無法解析的循環引用? –

0

最後我這樣做是爲了我的轉換器:

class BaseConverter { 
    @Autowired 
    ApplicationContext alpCtx; 
    public ConversionService getConversaionService(){ 
     alpCtx.getBean("conversionService"); 
    } 
} 
class APojToADbo extends BaseConverter implements Converter<>{ 
    convert(){ 
     getConversaionService() //return lookup from alpCtx and return from Baseclass 
    } 
}