org.springframework.core.convert.support.GenericConversionService#addConverter ( )源码实例Demo

下面列出了org.springframework.core.convert.support.GenericConversionService#addConverter ( ) 实例代码,或者点击链接到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");
}
 
源代码2 项目: spring-analysis-note   文件: OpPlusTests.java
@Test
public void test_binaryPlusWithTimeConverted() {
	SimpleDateFormat format = new SimpleDateFormat("hh :--: mm :--: ss", Locale.ENGLISH);

	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(Time.class, String.class, format::format);

	StandardEvaluationContext evaluationContextConverter = new StandardEvaluationContext();
	evaluationContextConverter.setTypeConverter(new StandardTypeConverter(conversionService));

	ExpressionState expressionState = new ExpressionState(evaluationContextConverter);
	Time time = new Time(new Date().getTime());

	VariableReference var = new VariableReference("timeVar", -1, -1);
	var.setValue(expressionState, time);

	StringLiteral n2 = new StringLiteral("\" is now\"", -1, -1, "\" is now\"");
	OpPlus o = new OpPlus(-1, -1, var, n2);
	TypedValue value = o.getValueInternal(expressionState);

	assertEquals(String.class, value.getTypeDescriptor().getObjectType());
	assertEquals(String.class, value.getTypeDescriptor().getType());
	assertEquals(format.format(time) + " is now", value.getValue());
}
 
@Test
public void testCustomConverter() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new Converter<String, Float>() {
		@Override
		public Float convert(String source) {
			try {
				NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
				return nf.parse(source).floatValue();
			}
			catch (ParseException ex) {
				throw new IllegalArgumentException(ex);
			}
		}
	});
	lbf.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,1");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
源代码4 项目: spring-data-crate   文件: CustomConversions.java
/**
 * Populates the given {@link GenericConversionService} with the converters registered.
 *
 * @param conversionService the service to register.
 */
public void registerConvertersIn(final GenericConversionService conversionService) {
  for (Object converter : converters) {
    boolean added = false;

    if (converter instanceof Converter) {
      conversionService.addConverter((Converter<?, ?>) converter);
      added = true;
    }

    if (converter instanceof ConverterFactory) {
      conversionService.addConverterFactory((ConverterFactory<?, ?>) converter);
      added = true;
    }

    if (converter instanceof GenericConverter) {
      conversionService.addConverter((GenericConverter) converter);
      added = true;
    }

    if (!added) {
      throw new IllegalArgumentException("Given set contains element that is neither Converter nor ConverterFactory!");
    }
  }
}
 
@Test
public void noDelegateMapConversion() {
	GenericConversionService conversionService = new GenericConversionService();
	GenericMapConverter mapConverter = new GenericMapConverter(conversionService);
	conversionService.addConverter(mapConverter);

	@SuppressWarnings("unchecked")
	Map<String, String> result = conversionService.convert("foo = bar, wizz = jogg", Map.class);
	assertThat(result, hasEntry("foo", "bar"));
	assertThat(result, hasEntry("wizz", "jogg"));

	assertThat(
			conversionService.canConvert(TypeDescriptor.valueOf(String.class), TypeDescriptor.map(Map.class,
					TypeDescriptor.valueOf(GenericMapConverterTests.class), TypeDescriptor.valueOf(Integer.class))),
			is(false));
}
 
@Test
public void testCustomConverter() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new Converter<String, Float>() {
		@Override
		public Float convert(String source) {
			try {
				NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
				return nf.parse(source).floatValue();
			}
			catch (ParseException ex) {
				throw new IllegalArgumentException(ex);
			}
		}
	});
	lbf.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,1");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
源代码7 项目: erp-framework   文件: WebConfig.java
/**
 * 增加字符串转日期的功能
 */
@PostConstruct
public void initEditableValidation() {
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
            .getWebBindingInitializer();
    if (initializer.getConversionService() != null) {
        GenericConversionService genericConversionService = (GenericConversionService) initializer
                .getConversionService();
        genericConversionService.addConverter(new DateConverter());
    }
}
 
@Test
public void prototypeCreationReevaluatesExpressions() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
	GenericConversionService cs = new GenericConversionService();
	cs.addConverter(String.class, String.class, String::trim);
	ac.getBeanFactory().registerSingleton(GenericApplicationContext.CONVERSION_SERVICE_BEAN_NAME, cs);
	RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.getPropertyValues().add("country", "#{systemProperties.country}");
	rbd.getPropertyValues().add("country2", new TypedStringValue("-#{systemProperties.country}-"));
	ac.registerBeanDefinition("test", rbd);
	ac.refresh();

	try {
		System.getProperties().put("name", "juergen1");
		System.getProperties().put("country", " UK1 ");
		PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen1", tb.getName());
		assertEquals("UK1", tb.getCountry());
		assertEquals("-UK1-", tb.getCountry2());

		System.getProperties().put("name", "juergen2");
		System.getProperties().put("country", "  UK2  ");
		tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen2", tb.getName());
		assertEquals("UK2", tb.getCountry());
		assertEquals("-UK2-", tb.getCountry2());
	}
	finally {
		System.getProperties().remove("name");
		System.getProperties().remove("country");
	}
}
 
@Bean
public ConversionService webSocketConversionService() {
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new MyTypeToStringConverter());
	conversionService.addConverter(new MyTypeToBytesConverter());
	conversionService.addConverter(new StringToMyTypeConverter());
	conversionService.addConverter(new BytesToMyTypeConverter());
	return conversionService;
}
 
源代码10 项目: youkefu   文件: WebConfigBeans.java
/**
 * 增加字符串转日期的功能
 */
@PostConstruct
public void initEditableValidation() {
	
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
        .getWebBindingInitializer();
    if (initializer.getConversionService() != null) {
        GenericConversionService genericConversionService = (GenericConversionService) initializer
            .getConversionService();
        genericConversionService.addConverter(new StringToDateConverter());
    }

}
 
@Test
public void prototypeCreationReevaluatesExpressions() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
	GenericConversionService cs = new GenericConversionService();
	cs.addConverter(String.class, String.class, String::trim);
	ac.getBeanFactory().registerSingleton(GenericApplicationContext.CONVERSION_SERVICE_BEAN_NAME, cs);
	RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.getPropertyValues().add("country", "#{systemProperties.country}");
	rbd.getPropertyValues().add("country2", new TypedStringValue("-#{systemProperties.country}-"));
	ac.registerBeanDefinition("test", rbd);
	ac.refresh();

	try {
		System.getProperties().put("name", "juergen1");
		System.getProperties().put("country", " UK1 ");
		PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen1", tb.getName());
		assertEquals("UK1", tb.getCountry());
		assertEquals("-UK1-", tb.getCountry2());

		System.getProperties().put("name", "juergen2");
		System.getProperties().put("country", "  UK2  ");
		tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen2", tb.getName());
		assertEquals("UK2", tb.getCountry());
		assertEquals("-UK2-", tb.getCountry2());
	}
	finally {
		System.getProperties().remove("name");
		System.getProperties().remove("country");
	}
}
 
源代码12 项目: java-technology-stack   文件: OpPlusTests.java
@Test
public void test_binaryPlusWithTimeConverted() {

	final SimpleDateFormat format = new SimpleDateFormat("hh :--: mm :--: ss", Locale.ENGLISH);

	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(new Converter<Time, String>() {
		@Override
		public String convert(Time source) {
			return format.format(source);
		}
	});

	StandardEvaluationContext evaluationContextConverter = new StandardEvaluationContext();
	evaluationContextConverter.setTypeConverter(new StandardTypeConverter(conversionService));

	ExpressionState expressionState = new ExpressionState(evaluationContextConverter);

	Time time = new Time(new Date().getTime());

	VariableReference var = new VariableReference("timeVar", -1);
	var.setValue(expressionState, time);

	StringLiteral n2 = new StringLiteral("\" is now\"", -1, "\" is now\"");
	OpPlus o = new OpPlus(-1, var, n2);
	TypedValue value = o.getValueInternal(expressionState);

	assertEquals(String.class, value.getTypeDescriptor().getObjectType());
	assertEquals(String.class, value.getTypeDescriptor().getType());
	assertEquals(format.format(time) + " is now", value.getValue());
}
 
@Bean
public ConversionService webSocketConversionService() {
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new MyTypeToStringConverter());
	conversionService.addConverter(new MyTypeToBytesConverter());
	conversionService.addConverter(new StringToMyTypeConverter());
	conversionService.addConverter(new BytesToMyTypeConverter());
	return conversionService;
}
 
源代码14 项目: spring4-understanding   文件: OpPlusTests.java
@Test
public void test_binaryPlusWithTimeConverted() {

	final SimpleDateFormat format = new SimpleDateFormat("hh :--: mm :--: ss", Locale.ENGLISH);

	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(new Converter<Time, String>() {
		@Override
		public String convert(Time source) {
			return format.format(source);
		}
	});

	StandardEvaluationContext evaluationContextConverter = new StandardEvaluationContext();
	evaluationContextConverter.setTypeConverter(new StandardTypeConverter(conversionService));

	ExpressionState expressionState = new ExpressionState(evaluationContextConverter);

	Time time = new Time(new Date().getTime());

	VariableReference var = new VariableReference("timeVar", -1);
	var.setValue(expressionState, time);

	StringLiteral n2 = new StringLiteral("\" is now\"", -1, "\" is now\"");
	OpPlus o = new OpPlus(-1, var, n2);
	TypedValue value = o.getValueInternal(expressionState);

	assertEquals(String.class, value.getTypeDescriptor().getObjectType());
	assertEquals(String.class, value.getTypeDescriptor().getType());
	assertEquals(format.format(time) + " is now", value.getValue());
}
 
源代码15 项目: Guns   文件: String2DateConfig.java
/**
 * 默认时间转化器
 */
@PostConstruct
public void addConversionConfig() {
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
    if ((initializer != null ? initializer.getConversionService() : null) != null) {
        GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
        genericConversionService.addConverter(new StringToDateConverter());
    }
}
 
源代码16 项目: Resource   文件: ConfigurerAdapter.java
/**
 * 日期类型转换
 */
@PostConstruct
public void initEditableValidation()
{
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)adapter.getWebBindingInitializer();
    if (initializer.getConversionService() != null)
    {
        GenericConversionService service = (GenericConversionService)initializer.getConversionService();
        service.addConverter(new StringToDateConverter());
    }
}
 
源代码17 项目: spring4-understanding   文件: Spr7839Tests.java
@Before
public void setUp() {
	ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer();
	GenericConversionService service = new DefaultConversionService();
	service.addConverter(new Converter<String, NestedBean>() {
		@Override
		public NestedBean convert(String source) {
			return new NestedBean(source);
		}
	});
	binder.setConversionService(service);
	adapter.setWebBindingInitializer(binder);
}
 
源代码18 项目: rice   文件: DataDictionary.java
/**
 * Sets up the bean post processor and conversion service
 *
 * @param beans - The bean factory for the the dictionary beans
 */
public static void setupProcessor(DefaultListableBeanFactory beans) {
    try {
        // UIF post processor that sets component ids
        BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance();
        beans.addBeanPostProcessor(idPostProcessor);
        beans.setBeanExpressionResolver(new StandardBeanExpressionResolver() {
            @Override
            protected void customizeEvaluationContext(StandardEvaluationContext evalContext) {
                try {
                    evalContext.registerFunction("getService", ExpressionFunctions.class.getDeclaredMethod("getService", new Class[]{String.class}));
                } catch(NoSuchMethodException me) {
                    LOG.error("Unable to register custom expression to data dictionary bean factory", me);
                }
            }
        });

        // special converters for shorthand map and list property syntax
        GenericConversionService conversionService = new GenericConversionService();
        conversionService.addConverter(new StringMapConverter());
        conversionService.addConverter(new StringListConverter());

        beans.setConversionService(conversionService);
    } catch (Exception e1) {
        throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(),
                e1);
    }
}
 
private static GenericConversionService createDefaultConversionService() {
	GenericConversionService converter = new GenericConversionService();
	converter.addConverter(Object.class, byte[].class, new SerializingConverter());
	converter.addConverter(byte[].class, Object.class, new DeserializingConverter());
	return converter;
}
 
源代码20 项目: kfs   文件: DataDictionary.java
public void parseDataDictionaryConfigurationFiles( boolean allowConcurrentValidation ) {
    // configure the bean factory, setup component decorator post processor
    // and allow Spring EL
    try {
        BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance();
        ddBeans.addBeanPostProcessor(idPostProcessor);
        ddBeans.setBeanExpressionResolver(new StandardBeanExpressionResolver());

        GenericConversionService conversionService = new GenericConversionService();
        conversionService.addConverter(new StringMapConverter());
        conversionService.addConverter(new StringListConverter());
        ddBeans.setConversionService(conversionService);
    } catch (Exception e1) {
        LOG.error("Cannot create component decorator post processor: " + e1.getMessage(), e1);
        throw new RuntimeException("Cannot create component decorator post processor: " + e1.getMessage(), e1);
    }

    // expand configuration locations into files
    LOG.info("Starting DD XML File Load");

    String[] configFileLocationsArray = new String[configFileLocations.size()];
    configFileLocationsArray = configFileLocations.toArray(configFileLocationsArray);
    configFileLocations.clear(); // empty the list out so other items can be added
    try {
        xmlReader.loadBeanDefinitions(configFileLocationsArray);
    } catch (Exception e) {
        LOG.error("Error loading bean definitions", e);
        throw new DataDictionaryException("Error loading bean definitions: " + e.getLocalizedMessage());
    }
    LOG.info("Completed DD XML File Load");

    UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor();
    factoryPostProcessor.postProcessBeanFactory(ddBeans);

    // indexing
    if (allowConcurrentValidation) {
        Thread t = new Thread(ddIndex);
        t.start();

        Thread t2 = new Thread(uifIndex);
        t2.start();
    } else {
        ddIndex.run();
        uifIndex.run();
    }
}