java - 如何在 Spring 配置文件中初始化 boolean 值?

标签 java spring

事实上我已经寻找过这个问题的答案,但还没有找到解决方案。而且,我是一个十足的Spring菜鸟,继承了这个问题......

当我为项目部署 WAR 文件时,它未能引用从字符串到 boolean 值的转换。详情:

Spring 配置文件包含此(已编辑)元素:

<property name="logTypes">
    <map>
        <entry key="MESSAGE" value="${xxx.messagelogenabled}" />
        <entry key="SUMMARY" value="${xxx.summarylogenabled}" />
        <entry key="STATISTICS" value="true" />
        <entry key="ERROR" value="true" />
        <entry key="WARNING" value="true" />
        <entry key="DEBUG" value="${xxx.debuglogenabled}" />
    </map>
</property>

“xxx.*logenabled”字符串在其他地方定义为“true”或“false”,但即使我将这些引用替换为“true”,也会失败。

“logTypes”属性的 setter 是:

public void setLogTypes(Map<String, Boolean> logTypesMap)
{ /* I think the problem is with Spring creating the argument
     to this method, not the method itself */ }

我收到以下运行时错误,导致部署失败:

Error setting property values;
nested exception is org.springframework.beans.PropertyBatchUpdateException;
nested PropertyAccessExceptions (1) are:
   PropertyAccessException 1:
      org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.util.LinkedHashMap] to required type [java.util.Map] for property 'logTypes';
      nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean

这是我正在运行的 Java 版本:

% java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

最佳答案

您可以指定映射的键类型和值类型

<property name="logTypes">

    <map key-type="java.lang.String" value-type="java.lang.Boolean">

        <entry key="MESSAGE" value="${xxx.messagelogenabled}" />
        <entry key="SUMMARY" value="${xxx.summarylogenabled}" />
        <entry key="STATISTICS" value="true" />
        <entry key="ERROR" value="true" />
        <entry key="WARNING" value="true" />
        <entry key="DEBUG" value="${xxx.debuglogenabled}" />
    </map>
</property>

关于java - 如何在 Spring 配置文件中初始化 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31416457/

相关文章:

java - 如何匹配具有包含 "/"的 @pathVariable 的 Spring @RequestMapping?

java - Jenkins 构建环境与常规环境有何不同?

java - enum.ValueOf 需要完全限定路径吗?

java - 使用 .readlines() 方法时如何克服 "\n"

spring - 如何使用 Spring Data Elasticsearch ElasticsearchRepository 突出显示

java - 如何将 CXF 从 2.7 迁移到 3.0?

java - @PreAuthorize ("isAuthenticated()") 与 http.anyRequest().authenticated()

java - 在 WebSecurityConfigurerAdapter 中正确使用 WebSecurity

java - 如何从另一个带有值的类调用的另一个类获取函数的结果

java - charAt 用于确定唯一字符时