有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring启动应用程序。yml双反斜杠字面解释

我用的是Spring Boot 1.5.8

我的application.yml具有以下属性:

my:
  path: \\\\hostname\\dir

根据我从YAML spec 5.7. Escaped Characters中了解到的情况,双反斜杠\\是单个反斜杠的有效转义序列,因此上面的配置应该产生一个值my.path: \\hostname\dir

然而,在我的应用程序中,我可以看到该属性的值包含两个反斜杠:

@RunWith(SpringRunner.class)
@SpringBootTest
public class PropTest {

    @Getter
    @Setter
    public static class MyProp {
        private String path;
    }

    @Autowired
    private MyProp my;

    @Test
    public void testProp() {
        System.out.println(my.path);
    }

    @Configuration
    @EnableConfigurationProperties
    public static class Config {
        @Bean
        @ConfigurationProperties("my")
        public MyProp my() {
            return new MyProp();
        }
    }
}

印刷品:

\\\\host\\dir

我不能将application.yml中的值加引号,因为该文件是由供应系统(SaltStack)生成的,并且它有自己的Yaml渲染库

这是Spring Boot/Spring Boot使用的Yaml库中的错误吗?有没有办法强迫Spring Boot将Yaml中的双反斜杠视为单反斜杠的逃逸


共 (1) 个答案

  1. # 1 楼答案

    引用您链接的规格部分:

    Note that escape sequences are only interpreted in double-quoted scalars. In all other scalar styles, the “\” character has no special meaning and non-printable characters are not available.

    因此,如果你不双引号标量,\是一个普通字符,就像其他任何字符一样,你可以直接写

    my:
      path: \\hostname\dir