下面列出了org.springframework.core.convert.converter.ConverterFactory#org.springframework.core.convert.converter.Converter 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void customConversion() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
GenericConversionService conversionService = new GenericConversionService();
conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
@Override
public String convert(SampleBean source) {
return "foo bar";
}
});
instance.setConversionService(conversionService);
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "simpleString", String.class);
invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
assertMethodInvocation(sample, "simpleString");
}
public static Collection<Converter<?, ?>> getConvertersToRegister() {
if (!JODA_TIME_IS_PRESENT) {
return Collections.emptySet();
}
final List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(InstantToStringConverter.INSTANCE);
converters.add(DateTimeToStringConverter.INSTANCE);
converters.add(LocalDateToStringConverter.INSTANCE);
converters.add(LocalDateTimeToStringConverter.INSTANCE);
converters.add(StringToInstantConverter.INSTANCE);
converters.add(StringToDateTimeConverter.INSTANCE);
converters.add(StringToLocalDateConverter.INSTANCE);
converters.add(StringToLocalDateTimeConverter.INSTANCE);
return converters;
}
/**
* Register the given Converter objects with the given target ConverterRegistry.
* @param converters the converter objects: implementing {@link Converter},
* {@link ConverterFactory}, or {@link GenericConverter}
* @param registry the target registry
*/
public static void registerConverters(Set<?> converters, ConverterRegistry registry) {
if (converters != null) {
for (Object converter : converters) {
if (converter instanceof GenericConverter) {
registry.addConverter((GenericConverter) converter);
}
else if (converter instanceof Converter<?, ?>) {
registry.addConverter((Converter<?, ?>) converter);
}
else if (converter instanceof ConverterFactory<?, ?>) {
registry.addConverterFactory((ConverterFactory<?, ?>) converter);
}
else {
throw new IllegalArgumentException("Each converter object must implement one of the " +
"Converter, ConverterFactory, or GenericConverter interfaces");
}
}
}
}
@Test
public void customConversion() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
GenericConversionService conversionService = new GenericConversionService();
conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
@Override
public String convert(SampleBean source) {
return "foo bar";
}
});
instance.setConversionService(conversionService);
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "simpleString", String.class);
invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
assertMethodInvocation(sample, "simpleString");
}
@Override
public JdbcCustomConversions jdbcCustomConversions() {
return new JdbcCustomConversions(asList(new Converter<Clob, String>() {
@Nullable
@Override
public String convert(Clob clob) {
try {
return Math.toIntExact(clob.length()) == 0 //
? "" //
: clob.getSubString(1, Math.toIntExact(clob.length()));
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert CLOB to String.", e);
}
}
}));
}
@Bean
public Converter<String, JsonNode> jsonNodeConverter() {
// Don't convert to lambda -> cause issue for Spring to infer source and target types.
return new Converter<String, JsonNode>() {
@Override
public JsonNode convert(String source) {
if (source.isEmpty()) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION,
new IllegalArgumentException("Source should not be empty"));
}
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readTree(source);
} catch (IOException e) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
}
};
}
public ConversionService create() {
if (this.converters.isEmpty() && this.genericConverters.isEmpty()) {
return ApplicationConversionService.getSharedInstance();
}
ApplicationConversionService conversionService = new ApplicationConversionService();
for (Converter<?, ?> converter : this.converters) {
conversionService.addConverter(converter);
}
for (GenericConverter genericConverter : this.genericConverters) {
conversionService.addConverter(genericConverter);
}
return conversionService;
}
/**
* copy 不做类型转换
*/
public void copy2(User user, Map<String, Object> userMap, Converter var3) {
Object id = userMap.get("id");
if (id != null) {
// 不做类型转换生成的代码
if (ClassUtil.isAssignableValue(Integer.class, id)) {
// 此处 需要 asm 做 类型转换 判断
user.setId((Integer) id);
}
}
}
@Test
public void formatFieldForTypeWithPrinterParserWithCoercion() throws ParseException {
formattingService.addConverter(new Converter<DateTime, LocalDate>() {
@Override
public LocalDate convert(DateTime source) {
return source.toLocalDate();
}
});
formattingService.addFormatterForFieldType(LocalDate.class, new ReadablePartialPrinter(DateTimeFormat
.shortDate()), new DateTimeParser(DateTimeFormat.shortDate()));
String formatted = formattingService.convert(new LocalDate(2009, 10, 31), String.class);
assertEquals("10/31/09", formatted);
LocalDate date = formattingService.convert("10/31/09", LocalDate.class);
assertEquals(new LocalDate(2009, 10, 31), date);
}
@Override
@SuppressWarnings("unchecked")
public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
if (Integer.class == targetType) {
return (Converter<String, T>) new IntegerConverter();
}
else {
throw new IllegalStateException();
}
}
public SpringLockConfigurationExtractor(
@NonNull Duration defaultLockAtMostFor,
@NonNull Duration defaultLockAtLeastFor,
@Nullable StringValueResolver embeddedValueResolver,
@NonNull Converter<String, Duration> durationConverter
) {
this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor);
this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor);
this.durationConverter = requireNonNull(durationConverter);
this.embeddedValueResolver = embeddedValueResolver;
}
@Bean
public CustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new DateToZonedDateTimeConverter());
converters.add(new ZonedDateTimeToDateConverter());
return new CustomConversions(converters);
}
public Converter<Long, Group> getIdToGroupConverter() {
return new Converter<java.lang.Long, Group>() {
public Group convert(java.lang.Long id) {
log.info("converting Long to Group id=" + id + " result" + userService.group_findById(id).toString());
return userService.group_findById(id);
}
};
}
public Converter<String, Group> getStringToGroupConverter() {
return new Converter<java.lang.String, Group>() {
public Group convert(String id) {
log.info("converting String to Group id=" + id);
return getObject().convert(getObject().convert(id, Long.class), Group.class);
}
};
}
public Converter<RegularExpression, String> getRegularExpressionToStringConverter() {
return new Converter<RegularExpression, java.lang.String>() {
public String convert(RegularExpression regularExpression) {
log.info("converting regularExpressionToString");
return new StringBuilder().append(regularExpression.getName()).toString();
}
};
}
public Converter<String, VelocityTemplate> getStringToVelocityTemplateConverter() {
return new Converter<java.lang.String, VelocityTemplate>() {
public VelocityTemplate convert(String id) {
log.info("converting String to VelocityTemplate id=" + id);
return getObject().convert(getObject().convert(id, Long.class), VelocityTemplate.class);
}
};
}
@Test
public void testServiceDefinitionToConsulRegistration() throws Exception {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE)
.run(
"--debug=false",
"--spring.main.banner-mode=OFF",
"--spring.application.name=" + UUID.randomUUID().toString(),
"--ribbon.enabled=false",
"--ribbon.eureka.enabled=false",
"--management.endpoint.enabled=false",
"--spring.cloud.consul.enabled=true",
"--spring.cloud.consul.config.enabled=false",
"--spring.cloud.consul.discovery.enabled=true",
"--spring.cloud.service-registry.auto-registration.enabled=false",
"--spring.main.allow-bean-definition-overriding=true"
);
// TODO: Remove --spring.main.allow-bean-definition-overriding=true when new version of spring-cloud
// is released that supports Spring Boot 2.1 more properly
try {
Map<String, Converter> converters = context.getBeansOfType(Converter.class);
assertThat(converters).isNotNull();
assertThat(converters.values().stream().anyMatch(ServiceDefinitionToConsulRegistration.class::isInstance)).isTrue();
} finally {
context.close();
}
}
@Test
public void testConsulServerToServiceDefinition() throws Exception {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE)
.run(
"--debug=false",
"--spring.main.banner-mode=OFF",
"--spring.application.name=" + UUID.randomUUID().toString(),
"--ribbon.enabled=false",
"--ribbon.eureka.enabled=false",
"--management.endpoint.enabled=false",
"--spring.cloud.consul.enabled=true",
"--spring.cloud.consul.config.enabled=false",
"--spring.cloud.consul.discovery.enabled=true",
"--spring.cloud.service-registry.auto-registration.enabled=false",
"--spring.main.allow-bean-definition-overriding=true"
);
// TODO: Remove --spring.main.allow-bean-definition-overriding=true when new version of spring-cloud
// is released that supports Spring Boot 2.1 more properly
try {
Map<String, Converter> converters = context.getBeansOfType(Converter.class);
assertThat(converters).isNotNull();
assertThat(converters.values().stream().anyMatch(ConsulServerToServiceDefinition.class::isInstance)).isTrue();
} finally {
context.close();
}
}
@Test
public void testServiceDefinitionToConsulRegistration() throws Exception {
final ZookeeperServer server = new ZookeeperServer(temporaryFolder.newFolder(testName.getMethodName()));
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE)
.run(
"--debug=false",
"--spring.main.banner-mode=OFF",
"--spring.application.name=" + UUID.randomUUID().toString(),
"--ribbon.enabled=false",
"--ribbon.eureka.enabled=false",
"--management.endpoint.enabled=false",
"--spring.cloud.zookeeper.enabled=true",
"--spring.cloud.zookeeper.connect-string=" + server.connectString(),
"--spring.cloud.zookeeper.config.enabled=false",
"--spring.cloud.zookeeper.discovery.enabled=true",
"--spring.cloud.service-registry.auto-registration.enabled=false"
);
try {
Map<String, Converter> converters = context.getBeansOfType(Converter.class);
assertThat(converters).isNotNull();
assertThat(converters.values().stream().anyMatch(ServiceDefinitionToZookeeperRegistration.class::isInstance)).isTrue();
} finally {
// shutdown spring context
context.close();
// shutdown zookeeper
server.shutdown();
}
}
@Test
public void convertCannotOptimizeArray() {
conversionService.addConverter(new Converter<Byte, Byte>() {
@Override
public Byte convert(Byte source) {
return (byte) (source + 1);
}
});
byte[] byteArray = new byte[] { 1, 2, 3 };
byte[] converted = conversionService.convert(byteArray, byte[].class);
assertNotSame(byteArray, converted);
assertTrue(Arrays.equals(new byte[] { 2, 3, 4 }, converted));
}
public Converter<Long, DataSet> getIdToDataSetConverter() {
return new Converter<java.lang.Long, DataSet>() {
public DataSet convert(java.lang.Long id) {
log.info("converting Long to DataSet id=" + id + " result" + surveySettingsService.velocityTemplate_findById(id).toString());
return surveySettingsService.dataSet_findById(id);
}
};
}
public <T> T processResult(@Nullable Object source, Converter<Object, Object> preparingConverter) {
if (source == null || type.isInstance(source) || !type.isProjecting()) {
return (T) source;
}
Assert.notNull(preparingConverter, "Preparing converter must not be null!");
ChainingConverter converter = ChainingConverter.of(type.getReturnedType(), preparingConverter).and(this.converter);
if (source instanceof Slice ) {
return (T) ((Slice<?>) source).map(converter::convert);
}
if (source instanceof Collection ) {
Collection<?> collection = (Collection<?>) source;
Collection<Object> target = createCollectionFor(collection);
for (Object columns : collection) {
target.add(type.isInstance(columns) ? columns : converter.convert(columns));
}
return (T) target;
}
return (T) converter.convert(source);
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<TestBean, String>() {
@Override
public String convert(TestBean source) {
return "converted";
}
});
}
/**
* 日期参数接收转换器,将json字符串转为日期类型
*
* @return MVC LocalDate 参数接收转换器
*/
@Bean
public Converter<String, LocalDate> localDateConvert() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateUtils.DATE_FORMATTER);
}
};
}
public Converter<GroupingOperator, String> geGroupingOperatorToStringConverter() {
return new Converter<GroupingOperator, java.lang.String>() {
public String convert(GroupingOperator groupingOperator) {
log.info("converting QuestionTypeToString");
return groupingOperator.getCode();
}
};
}
public Converter<Sector, String> getSectorToStringConverter() {
return new Converter<Sector, java.lang.String>() {
public String convert(Sector sector) {
log.info("converting SectorToString");
return new StringBuilder().append(sector.getName()).toString();
}
};
}
public Converter<String, User> getStringToUserConverter() {
return new Converter<java.lang.String, User>() {
public User convert(String id) {
log.info("converting String to User id=" + id);
return getObject().convert(getObject().convert(id, Long.class), User.class);
}
};
}
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(DateToZonedDateTimeConverter.INSTANCE);
converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converterList);
}
@Test
public void formatFieldForTypeWithPrinterParserWithCoercion() throws ParseException {
formattingService.addConverter(new Converter<DateTime, LocalDate>() {
@Override
public LocalDate convert(DateTime source) {
return source.toLocalDate();
}
});
formattingService.addFormatterForFieldType(LocalDate.class, new ReadablePartialPrinter(DateTimeFormat
.shortDate()), new DateTimeParser(DateTimeFormat.shortDate()));
String formatted = formattingService.convert(new LocalDate(2009, 10, 31), String.class);
assertEquals("10/31/09", formatted);
LocalDate date = formattingService.convert("10/31/09", LocalDate.class);
assertEquals(new LocalDate(2009, 10, 31), date);
}
@Bean
public CassandraCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new PersonWriteConverter());
converters.add(new PersonReadConverter());
converters.add(new CustomAddressbookReadConverter());
converters.add(CurrencyToStringConverter.INSTANCE);
converters.add(StringToCurrencyConverter.INSTANCE);
return new CassandraCustomConversions(converters);
}