类org.springframework.core.convert.ConversionService源码实例Demo

下面列出了怎么用org.springframework.core.convert.ConversionService的API类实例代码及写法,或者点击链接到github查看源代码。

public ConversionService resolve(boolean requireToRegister) {

        ConversionService conversionService = getResolvedBeanIfAvailable();

        if (conversionService == null) { // If not resolved, try to get from ConfigurableBeanFactory
            conversionService = getFromBeanFactory();
        }

        if (conversionService == null) { // If not found, try to get the bean from BeanFactory
            debug("The conversionService instance can't be found in Spring ConfigurableBeanFactory.getConversionService()");
            conversionService = getIfAvailable();
        }
        if (conversionService == null) { // If not found, will create an instance of ConversionService as default
            conversionService = createDefaultConversionService();
        }

        if (!isBeanPresent(beanFactory, RESOLVED_CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)
                && requireToRegister) { // To register a singleton into SingletonBeanRegistry(ConfigurableBeanFactory)
            beanFactory.registerSingleton(RESOLVED_CONVERSION_SERVICE_BEAN_NAME, conversionService);
        }

        return conversionService;
    }
 
源代码2 项目: spring-cloud-gray   文件: ConfigurationUtils.java
public static void bind(Object o, Map<String, Object> properties,
                        String configurationPropertyName, String bindingName, Validator validator,
                        ConversionService conversionService) {
    Object toBind = getTargetObject(o);

    new Binder(
            Collections.singletonList(new MapConfigurationPropertySource(properties)),
            null, conversionService).bind(configurationPropertyName,
            Bindable.ofInstance(toBind));

    if (validator != null) {
        BindingResult errors = new BeanPropertyBindingResult(toBind, bindingName);
        validator.validate(toBind, errors);
        if (errors.hasErrors()) {
            throw new RuntimeException(new BindException(errors));
        }
    }
}
 
/**
 * Create a model attribute from a String request value (e.g. URI template
 * variable, request parameter) using type conversion.
 * <p>The default implementation converts only if there a registered
 * {@link Converter} that can perform the conversion.
 * @param sourceValue the source value to create the model attribute from
 * @param attributeName the name of the attribute (never {@code null})
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, or {@code null} if no suitable
 * conversion found
 */
@Nullable
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
		MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request)
		throws Exception {

	DataBinder binder = binderFactory.createBinder(request, null, attributeName);
	ConversionService conversionService = binder.getConversionService();
	if (conversionService != null) {
		TypeDescriptor source = TypeDescriptor.valueOf(String.class);
		TypeDescriptor target = new TypeDescriptor(parameter);
		if (conversionService.canConvert(source, target)) {
			return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
		}
	}
	return null;
}
 
/**
 * Add common collection converters.
 * @param converterRegistry the registry of converters to add to
 * (must also be castable to ConversionService, e.g. being a {@link ConfigurableConversionService})
 * @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
 * @since 4.2.3
 */
public static void addCollectionConverters(ConverterRegistry converterRegistry) {
	ConversionService conversionService = (ConversionService) converterRegistry;

	converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));
	converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));
	converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));
	converterRegistry.addConverter(new MapToMapConverter(conversionService));

	converterRegistry.addConverter(new ArrayToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));

	converterRegistry.addConverter(new CollectionToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToCollectionConverter(conversionService));

	converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));

	converterRegistry.addConverter(new StreamConverter(conversionService));
}
 
源代码5 项目: FastBootWeixin   文件: WxApiParamContributor.java
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
    Class<?> paramType = parameter.getNestedParameterType();
    if (Map.class.isAssignableFrom(paramType)) {
        return;
    }
    WxApiParam wxApiParam = parameter.getParameterAnnotation(WxApiParam.class);
    String name = (wxApiParam == null || StringUtils.isEmpty(wxApiParam.name()) ? parameter.getParameterName() : wxApiParam.name());
    WxAppAssert.notNull(name, "请添加编译器的-parameter或者为参数添加注解名称");
    if (value == null) {
        if (wxApiParam != null) {
            if (!wxApiParam.required() || !wxApiParam.defaultValue().equals(ValueConstants.DEFAULT_NONE)) {
                return;
            }
        }
        builder.queryParam(name);
    } else if (value instanceof Collection) {
        for (Object element : (Collection<?>) value) {
            element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
            builder.queryParam(name, element);
        }
    } else {
        builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
    }
}
 
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	Class<?> paramType = parameter.getParameterType();
	if (Map.class.isAssignableFrom(paramType) || MultipartFile.class == paramType ||
			"javax.servlet.http.Part".equals(paramType.getName())) {
		return;
	}

	RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
	String name = (requestParam == null || StringUtils.isEmpty(requestParam.name()) ? parameter.getParameterName() : requestParam.name());

	if (value == null) {
		builder.queryParam(name);
	}
	else if (value instanceof Collection) {
		for (Object element : (Collection<?>) value) {
			element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
			builder.queryParam(name, element);
		}
	}
	else {
		builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
	}
}
 
源代码7 项目: spring-content   文件: DefaultJpaStoreImpl.java
protected Object convertToExternalContentIdType(S property, Object contentId) {
	ConversionService converter = new DefaultConversionService();
	if (converter.canConvert(TypeDescriptor.forObject(contentId),
			TypeDescriptor.valueOf(BeanUtils.getFieldWithAnnotationType(property,
					ContentId.class)))) {
		contentId = converter.convert(contentId, TypeDescriptor.forObject(contentId),
				TypeDescriptor.valueOf(BeanUtils.getFieldWithAnnotationType(property,
						ContentId.class)));
		return contentId;
	}
	return contentId.toString();
}
 
源代码8 项目: openemm   文件: BounceFilterController.java
public BounceFilterController(@Qualifier("BounceFilterService") BounceFilterService bounceFilterService, @Qualifier("MailingBaseService") ComMailingBaseService mailingService,
                              final MailinglistApprovalService mailinglistApprovalService,
                              ComUserformService userFormService, ConversionService conversionService,
                              WebStorage webStorage,
                              UserActivityLogService userActivityLogService) {
    this.bounceFilterService = bounceFilterService;
    this.mailingService = mailingService;
    this.userFormService = userFormService;
    this.conversionService = conversionService;
    this.webStorage = webStorage;
    this.userActivityLogService = userActivityLogService;
    this.mailinglistApprovalService = mailinglistApprovalService;
}
 
源代码9 项目: openemm   文件: UserGroupController.java
public UserGroupController(UserGroupService userGroupService, WebStorage webStorage, ConfigService configService, UserActivityLogService userActivityLogService, ConversionService conversionService) {
    this.userGroupService = userGroupService;
    this.webStorage = webStorage;
    this.configService = configService;
    this.userActivityLogService = userActivityLogService;
    this.conversionService = conversionService;
}
 
源代码10 项目: camel-spring-boot   文件: SpringTypeConverter.java
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    // do not attempt to convert Camel types
    if (type.getCanonicalName().startsWith("org.apache")) {
        return null;
    }
    
    // do not attempt to convert List -> Map. Ognl expression may use this converter as a fallback expecting null
    if (type.isAssignableFrom(Map.class) && isArrayOrCollection(value)) {
        return null;
    }

    TypeDescriptor sourceType = types.computeIfAbsent(value.getClass(), TypeDescriptor::valueOf);
    TypeDescriptor targetType = types.computeIfAbsent(type, TypeDescriptor::valueOf);

    for (ConversionService conversionService : conversionServices) {
        if (conversionService.canConvert(sourceType, targetType)) {
            try {
                return (T)conversionService.convert(value, sourceType, targetType);
            } catch (ConversionFailedException e) {
                // if value is a collection or an array the check ConversionService::canConvert
                // may return true but then the conversion of specific objects may fail
                //
                // https://issues.apache.org/jira/browse/CAMEL-10548
                // https://jira.spring.io/browse/SPR-14971
                //
                if (e.getCause() instanceof ConverterNotFoundException && isArrayOrCollection(value)) {
                    return null;
                } else {
                    throw new TypeConversionException(value, type, e);
                }
            }
        }
    }

    return null;
}
 
@Test
public void createBinderWithGlobalInitialization() throws Exception {
	ConversionService conversionService = new DefaultFormattingConversionService();
	bindingInitializer.setConversionService(conversionService);

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	BindingContext context = createBindingContext("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);

	assertSame(conversionService, dataBinder.getConversionService());
}
 
@ConditionalOnMissingBean
@Bean
ConversionService defaultCamelConversionService(ApplicationContext applicationContext) {
    DefaultConversionService service = new DefaultConversionService();
    for (Converter converter : applicationContext.getBeansOfType(Converter.class).values()) {
        service.addConverter(converter);
    }
    return service;
}
 
源代码13 项目: springlets   文件: EntityExpressionSupport.java
public EntityExpressionSupport(ExpressionParser parser,
    TemplateParserContext templateParserContext, ConversionService conversionService,
    String defaultExpression) {
  this.parser = parser;
  this.templateParserContext = templateParserContext;
  this.defaultExpression = defaultExpression;
  this.conversionService = conversionService;
}
 
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "requestMappingHandlerAdapter";
	RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	List<HttpMessageReader<?>> readers = adapter.getMessageReaders();
	assertEquals(13, readers.size());

	ResolvableType multiValueMapType = forClassWithGenerics(MultiValueMap.class, String.class, String.class);

	assertHasMessageReader(readers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(String.class), TEXT_PLAIN);
	assertHasMessageReader(readers, forClass(Resource.class), IMAGE_PNG);
	assertHasMessageReader(readers, forClass(Message.class), new MediaType("application", "x-protobuf"));
	assertHasMessageReader(readers, multiValueMapType, APPLICATION_FORM_URLENCODED);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_XML);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_JSON);
	assertHasMessageReader(readers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
	assertHasMessageReader(readers, forClass(TestBean.class), null);

	WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer();
	assertNotNull(bindingInitializer);
	WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object());
	bindingInitializer.initBinder(binder);

	name = "webFluxConversionService";
	ConversionService service = context.getBean(name, ConversionService.class);
	assertSame(service, binder.getConversionService());

	name = "webFluxValidator";
	Validator validator = context.getBean(name, Validator.class);
	assertSame(validator, binder.getValidator());
}
 
public ConfigurationService(BeanFactory beanFactory,
		Supplier<ConversionService> conversionService,
		Supplier<Validator> validator) {
	this.beanFactory = beanFactory;
	this.conversionService = conversionService;
	this.validator = validator;
}
 
源代码16 项目: java-technology-stack   文件: DataBinder.java
/**
 * Specify a Spring 3.0 ConversionService to use for converting
 * property values, as an alternative to JavaBeans PropertyEditors.
 */
public void setConversionService(@Nullable ConversionService conversionService) {
	Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService");
	this.conversionService = conversionService;
	if (this.bindingResult != null && conversionService != null) {
		this.bindingResult.initConversion(conversionService);
	}
}
 
@Test
public void testCreateDefaultConversionService() {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ConversionServiceResolver resolver = new ConversionServiceResolver(beanFactory);
    ConversionService conversionService = resolver.resolve(false);
    assertTrue(isAssignable(DefaultFormattingConversionService.class, conversionService.getClass()));

    conversionService = resolver.resolve(true);
    assertTrue(isAssignable(DefaultFormattingConversionService.class, conversionService.getClass()));

    conversionService = resolver.resolve();
    assertTrue(isAssignable(DefaultFormattingConversionService.class, conversionService.getClass()));
}
 
public ConversionService getConversionService() {
    try {
        return this.applicationContext.getBean(
                ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME,
                ConversionService.class);
    } catch (NoSuchBeanDefinitionException ex) {
        return new Factory(this.applicationContext.getAutowireCapableBeanFactory())
                .create();
    }
}
 
@Before
public void setup() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
/**
 * A constructor accepting a {@code ConversionService} as well as a default
 * charset.
 *
 * @param conversionService the conversion service
 * @param defaultCharset the default charset
 */
public ObjectToStringHttpMessageConverter(ConversionService conversionService, Charset defaultCharset) {
	super(new MediaType("text", "plain", defaultCharset));

	Assert.notNull(conversionService, "conversionService is required");
	this.conversionService = conversionService;
	this.stringHttpMessageConverter = new StringHttpMessageConverter(defaultCharset);
}
 
源代码21 项目: spring4-understanding   文件: MimeTypeTests.java
@Test
public void withConversionService() {
	ConversionService conversionService = new DefaultConversionService();
	assertTrue(conversionService.canConvert(String.class, MimeType.class));
	MimeType mimeType = MimeType.valueOf("application/xml");
	assertEquals(mimeType, conversionService.convert("application/xml", MimeType.class));
}
 
源代码22 项目: lams   文件: ConvertingPropertyEditorAdapter.java
/**
 * Create a new ConvertingPropertyEditorAdapter for a given
 * {@link org.springframework.core.convert.ConversionService}
 * and the given target type.
 * @param conversionService the ConversionService to delegate to
 * @param targetDescriptor the target type to convert to
 */
public ConvertingPropertyEditorAdapter(ConversionService conversionService, TypeDescriptor targetDescriptor) {
	Assert.notNull(conversionService, "ConversionService must not be null");
	Assert.notNull(targetDescriptor, "TypeDescriptor must not be null");
	this.conversionService = conversionService;
	this.targetDescriptor = targetDescriptor;
	this.canConvertToString = conversionService.canConvert(this.targetDescriptor, TypeDescriptor.valueOf(String.class));
}
 
源代码23 项目: spring-analysis-note   文件: EvalTag.java
private EvaluationContext createEvaluationContext(PageContext pageContext) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
	context.addPropertyAccessor(new MapAccessor());
	context.addPropertyAccessor(new EnvironmentAccessor());
	context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
	ConversionService conversionService = getConversionService(pageContext);
	if (conversionService != null) {
		context.setTypeConverter(new StandardTypeConverter(conversionService));
	}
	return context;
}
 
@Before
public void setUp() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
/**
 * Add collection converters.
 * @param converterRegistry the registry of converters to add to (must also be castable to ConversionService,
 * e.g. being a {@link ConfigurableConversionService})
 * @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
 * @since 4.2.3
 */
public static void addCollectionConverters(ConverterRegistry converterRegistry) {
	ConversionService conversionService = (ConversionService) converterRegistry;

	converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));
	converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));
	converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));
	converterRegistry.addConverter(new MapToMapConverter(conversionService));

	converterRegistry.addConverter(new ArrayToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));

	converterRegistry.addConverter(new CollectionToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToCollectionConverter(conversionService));

	converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));

	if (streamAvailable) {
		converterRegistry.addConverter(new StreamConverter(conversionService));
	}
}
 
@Test
public void createDefaultConversionService() {
	ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
	factory.afterPropertiesSet();
	ConversionService service = factory.getObject();
	assertTrue(service.canConvert(String.class, Integer.class));
}
 
源代码27 项目: venus-cloud-feign   文件: VenusFeignAutoConfig.java
@Bean
public VenusSpringMvcContract feignSpringMvcContract(@Autowired(required = false) List<AnnotatedParameterProcessor> parameterProcessors,
                                                     ConversionService conversionService) {
    if (null == parameterProcessors) {
        parameterProcessors = new ArrayList<>();
    }
    return new VenusSpringMvcContract(parameterProcessors, conversionService);
}
 
@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;
}
 
@Test
public void defaultCharsetModified() throws IOException {
	ConversionService cs = new DefaultConversionService();
	ObjectToStringHttpMessageConverter converter = new ObjectToStringHttpMessageConverter(cs, StandardCharsets.UTF_16);
	converter.write((byte) 31, null, this.response);

	assertEquals("UTF-16", this.servletResponse.getCharacterEncoding());
}
 
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(12, converters.size());
	converters.stream()
			.filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter)
			.forEach(converter -> {
				ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
				assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
				if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
					assertEquals(XmlMapper.class, mapper.getClass());
				}
			});

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
 类所在包
 同包方法