Close

Spring Framework - Converter Examples

Spring Framework 

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

public class TradeIdToTradeConverter implements Converter<String, Trade> {

private TradeService tradeService;

public TradeIdToTradeConverter (TradeService tradeService) {
this.tradeService = tradeService;
}

@Override
public Trade convert (String id) {
try {
Long tradeId = Long.valueOf(id);
return tradeService.getTradeById(tradeId);
} catch (NumberFormatException e) {
return null;
}
}
Original Post




This example shows how to create a custom implementation of Converter used in a spring core application.

package com.logicbig.example;


import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class CustomConverterExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(
Config.class);

ClientBean clientBean = context.getBean(ClientBean.class);
clientBean.showLocalDateTime();
}

}

Output

2010-10-05
package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import java.time.LocalDate;

public class ClientBean {
private final String date;
@Autowired
private ConversionService conversionService;

ClientBean(String date) {
this.date = date;
}

public void showLocalDateTime() {
LocalDate localDate = conversionService.convert(date, LocalDate.class);
System.out.println(localDate);
}
}
package com.logicbig.example;

import org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class StringToLocalDateConverter
implements Converter<String, LocalDate> {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

@Override
public LocalDate convert(String dateTimeString) {
return LocalDate.parse(dateTimeString, formatter);
}
}
package com.logicbig.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;

@Configuration
public class Config {
@Bean
public ConversionService conversionService() {
DefaultConversionService service = new DefaultConversionService();
service.addConverter(new StringToLocalDateConverter());
return service;
}

@Bean
public ClientBean clientBean() {
return new ClientBean("2010/10/05");
}
}
Original Post




See Also