Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 尽管已注册,但未找到spring 3.0自定义通用转换器。错误:未找到匹配的编辑器或转换策略_Spring Mvc_Typeconverter - Fatal编程技术网

Spring mvc 尽管已注册,但未找到spring 3.0自定义通用转换器。错误:未找到匹配的编辑器或转换策略

Spring mvc 尽管已注册,但未找到spring 3.0自定义通用转换器。错误:未找到匹配的编辑器或转换策略,spring-mvc,typeconverter,Spring Mvc,Typeconverter,我创建了一个StringToMapConverter,用于将预定义格式的字符串转换为键值对映射。该键也可以是枚举类型 然而,在转换器中,我需要引用org.springframework.core.convert.ConversionService实例来将字符串转换为enum。因此,在myapp-servlet.xml上下文中,我尝试注册如下内容: <bean id="stringToMapConverter" class="com.myapp.util.StringToMapConvert

我创建了一个StringToMapConverter,用于将预定义格式的字符串转换为键值对映射。该键也可以是枚举类型

然而,在转换器中,我需要引用org.springframework.core.convert.ConversionService实例来将字符串转换为enum。因此,在myapp-servlet.xml上下文中,我尝试注册如下内容:

<bean id="stringToMapConverter" class="com.myapp.util.StringToMapConverter"/>

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <bean ref="stringToMapConverter" />
        </property>
</bean>
我调试了我的应用程序,发现转换器已成功添加到注册表中。但当需要将数据从java.lang.String转换为java.util.Map时,框架仍无法找到它

下面提到的是我编写的代码:

SearchResultsRefiner.java

 public class SearchResultsRefiner {

    private Map<SearchRefineFilter, String> filtersMap;

    public SearchResultsRefiner() {}


    public Map<SearchRefineFilter, String> getFiltersMap() {
        return filtersMap;
    }

    public void setFiltersMap(Map<SearchRefineFilter, String> filtersMap) {
        this.filtersMap = filtersMap;
    }

    }
服务器启动日志

 2012-01-19 20:37:08,108 INFO   [ContextLoader] Root WebApplicationContext: initialization started 
    2012-01-19 20:37:08,142 INFO   [XmlWebApplicationContext] Refreshing Root WebApplicationContext: startup date [Thu Jan 19 20:37:08 IST 2012]; root of context hierarchy 
    2012-01-19 20:37:08,201 INFO   [XmlBeanDefinitionReader] Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/util-context.xml] 
    2012-01-19 20:37:08,342 INFO   [XmlBeanDefinitionReader] Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/service-context.xml] 
    2012-01-19 20:37:08,677 INFO   [XmlBeanDefinitionReader] Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/persistence-context.xml] 
    2012-01-19 20:37:09,215 INFO   [PropertyPlaceholderConfigurer] Loading properties file from class path resource [fn-cars-bundle.properties] 
    2012-01-19 20:37:09,221 INFO   [PropertyPlaceholderConfigurer] Loading properties file from class path resource [fn-cars-bundle.properties] 
    2012-01-19 20:37:09,233 INFO   [DwrAnnotationPostProcessor] Detected candidate bean [asynchronousRequestHandlerServiceImpl]. Remoting using AsyncService 
    2012-01-19 20:37:09,246 INFO   [DwrAnnotationPostProcessor] Could not infer class for [conversionService]. Is it a factory bean? Omitting bean from annotation processing 
    2012-01-19 20:37:09,246 INFO   [DwrAnnotationPostProcessor] Could not infer class for [stringToMapConverter]. Is it a factory bean? Omitting bean from annotation processing 
    2012-01-19 20:37:09,436 INFO   [DefaultListableBeanFactory] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@aae8a: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,messageSource,memcachedClient,velocityEngine,smtpAuthenticator,mailSession,mailSender,converterConfig,resourceBundleUtil,dwrAnnotationPostProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#1,locationDAO,,dataSource,sessionFactory,txManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,conversionService,stringToMapConverter,__AsyncService,__dwrConfiguration]; root of factory hierarchy
串接变压器

 public class StringToMapConverter implements ConditionalGenericConverter {

    private static final String COMMA = ",";
    private static final String COLON = ":";

    private ConversionService conversionService;

    /**
     * @param conversionService the conversionService to set
     */
    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Map.class));
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        boolean matches = 
                this.conversionService.canConvert(sourceType, targetType.getMapKeyTypeDescriptor())
                 && this.conversionService.canConvert(sourceType, targetType.getMapValueTypeDescriptor());
        return matches;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object convert(Object source, TypeDescriptor sourceType,
            TypeDescriptor targetType) {

        if (source == null) {
            return null;
        }

        String sourceString = (String) source;

        if (sourceString.trim().isEmpty()) {
            return Collections.emptyMap();
        }

        @SuppressWarnings("rawtypes")
        Map targetMap = new HashMap();


        String[] keyValuePairs = sourceString.split(COMMA);
        String[] keyValueArr = null;
        String key = null;
        String value = null;
        for (String keyValuePair : keyValuePairs) {
            keyValueArr = keyValuePair.split(COLON);
            key = keyValueArr[0].trim();
            value = keyValueArr[1].trim();

            Object targetKey = 
                    this.conversionService.convert(
                            key, sourceType, targetType.getMapKeyTypeDescriptor(key));

            targetMap.put(targetKey, value);
        }       

        return targetMap;
    }

}
有谁能解释一下这种行为背后的原因,因为stringToMapConverter bean是按照上面所示的服务器启动日志创建的,以及如何解决这个问题

谢谢,
Jignesh

我已经解决了上面发布的问题,并将我的解决方案发布在这里以供参考

在发布导致错误的原因之前,我想显示由应用程序的DispatcherServlet加载的-servlet.xml上下文文件

-servlet.xml


我会尝试将您的XML更改为

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>    
            <bean id="stringToMapConverter" class="com.myapp.util.StringToMapConverter" />
        </set>
    </property>
</bean>

我的配置中有一些几乎相同的东西,它工作正常我不知道问题可能是缺少set标记,还是它没有处理bean ref的

我遇到了类似的问题,导致了相同的异常消息:

no matching editors or conversion strategy found
经检查,绑定中使用的conversionService似乎是默认的,而不是我配置为包含自定义转换器的服务

事实证明,我在两个不同的文件中声明了,而不带conversion service=conversionService的声明优先


有这种症状的人可能只想检查一下配置,然后再花几个小时把头撞在桌子上。

如果你想在新转换器上使用默认格式,而不是覆盖它,你可以这样做

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="path.to.SomeConverter"/>
        </set>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService" />

这是。

不管怎么说,我花了好几个小时把头撞在桌子上,但这才是罪魁祸首。非常感谢。抢手货为我们解决这个问题也可以看到:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

        <context:annotation-config />

        <context:component-scan base-package="<MY-PACKAGES>" />

        <!-- Handles GET requests for /resources/** by efficiently serving static content in the ${webappRoot}/resources dir -->
        <mvc:resources location="/resources/" mapping="/resources/**"/>

        <!--
            This tag registers the HandlerMapping and HandlerAdapter required to dispatch requests to your @Controllers. 
            In addition, it applies sensible defaults based on what is present in your classpath. Such defaults include:

            1) Using the Spring 3 Type ConversionService as a simpler and more robust alternative to JavaBeans PropertyEditors
            2) Support for formatting Number fields with @NumberFormat
            3) Support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath 
            4) Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath 
            5) Support for reading and writing XML, if JAXB is on the classpath 
            6) Support for reading and writing JSON, if Jackson is on the classpath   
         -->

         <!-- 
              We just require the converter feature not the formatting feature.Thus
              registering only the org.springframework.core.convert.support.GenericConversionService and 
              not org.springframework.format.support.FormattingConversionService which
              <mvc:annotation-driven> activates by default.Also we are registering
              a custom converter using the com.flightnetwork.cars.controller.util.ConverterConfig
              class 
         -->
        <!-- Added this to resolve my issue -->
        <mvc:annotation-driven conversion-service="conversionService"/> 

        <mvc:interceptors>
          <bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
              <property name="sessionFactory">
                  <ref bean="sessionFactory"/>
              </property>
              <property name="singleSession" value="false" />
          </bean>
        </mvc:interceptors>

        <!-- 
             Without the following adapter, we'll get a "Does your handler implement a supported interface like Controller?"
             This is because mvc:annotation-driven element doesn't declare a SimpleControllerHandlerAdapter
             For more info
             See http://stackoverflow.com/questions/3896013/no-adapter-for-handler-exception
             See http://forum.springsource.org/showthread.php?t=48372&highlight=UrlFilenameViewController    
        -->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

        <!-- 
              org.springframework.web.servlet.view.ResourceBundleViewResolver
              The bundle is typically defined in a properties file, 
              located in the class path. The default bundle basename is "views". 
        -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
             <property name="basename" value="views" />
        </bean>

        <!-- Added this to resolve my issue -->
        <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"/>
</beans>
    import java.util.Collections;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.DependsOn;
    import org.springframework.core.convert.ConversionService;
    import org.springframework.core.convert.converter.ConverterRegistry;
    import org.springframework.core.convert.support.ConversionServiceFactory;

    @Configuration
    public class ConverterConfig {

        @Autowired
        private ConversionService conversionService;

        @Autowired
        private ConverterRegistry converterRegistry;

        @Bean
        @DependsOn(value="conversionService")
        public StringToMapConverter stringToMapConverter() {
            StringToMapConverter stringToMapConverter = new StringToMapConverter();
            stringToMapConverter.setConversionService(this.conversionService);

            ConversionServiceFactory.registerConverters(
                    Collections.singleton(stringToMapConverter), this.converterRegistry);

            return stringToMapConverter;
        }
    }
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>    
            <bean id="stringToMapConverter" class="com.myapp.util.StringToMapConverter" />
        </set>
    </property>
</bean>
no matching editors or conversion strategy found
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="path.to.SomeConverter"/>
        </set>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService" />