spring3.0自定义通用转换器虽然已注册但未找到错误:找不到匹配的编辑器或转换策略

如何解决spring3.0自定义通用转换器虽然已注册但未找到错误:找不到匹配的编辑器或转换策略

我已经解决了上面发布的问题,并在此处发布了我的解决方案以供参考。

在发布导致错误的原因之前,我想显示 由我的应用程序的Dispatcher Servlet加载的 上下文文件。

<?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   
         -->

        <mvc:annotation-driven/>

        <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>

</beans>

从上面的文件中可以看出,我使用了 *

在Spring容器初始化时,属性值org.springframework.web.bind.support.ConfigurableWebBindingInitializer.setConversionService(ConversionService) 被设置为 org.springframework.format.support.FormattingConversionService 的实例,而不是org.springframework.core我 在其中注册了我的自定义转换器的.convert.support.GenericConversionService ,因此引发了错误, 。

但是到目前为止,我的应用程序中不需要格式转换服务,只想注册我的自定义转换器,因此为了实现我的目标,我使用了如下所示的更新代码:

<?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;
        }
    }

解决方法

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

但是在转换器中,我需要引用org.springframework.core.convert.ConversionService实例以将字符串转换为枚举,因此在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>

这使我陷入循环依赖错误,例如 “ conversionService:FactoryBean,当前正在创建中,它从getObject返回null”

因此,我尝试使用带有@Configuration注释的ConverterConverter类(我在下面提供的代码)来解决此循环依赖项错误,但现在我面临以下错误。

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'searchResultsRefiner' on field 'filtersMap': rejected value []; codes [typeMismatch.searchResultsRefiner.filtersMap,typeMismatch.filtersMap,typeMismatch.java.util.Map,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [searchResultsRefiner.filtersMap,filtersMap]; arguments []; default message [filtersMap]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Map' for property 'filtersMap'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Map] for property 'filtersMap': no matching editors or conversion strategy found]
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:810)
    at or

我调试了应用程序,发现转换器已成功添加到寄存器中,但是当需要数据从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;
    }

    }

ConverterConfig.java

  import java.util.Collections;

    @Configuration
    public class ConverterConfig {

    private ConversionService conversionService;
    private ConverterRegistry converterRegistry;

    @Bean
    public ConversionService conversionService() {
        this.conversionService = ConversionServiceFactory.createDefaultConversionService();
        this.converterRegistry = (GenericConversionService) this.conversionService;
        return conversionService;
    }


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

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

        return stringToMapConverter;
    }
    }

服务器启动日志

 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

StringToMapConverter

 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以及如何解决该问题?

谢谢,
吉涅什

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-