运行 spring 应用程序在 docker 容器中时变音符号不起作用

umlauts not working when running spring app in docker container

我在服务中有这个测试代码:

import io.r2dbc.postgresql.codec.Json

// ...

logger.info("test")
val x = "{\"x\": \"ü\"}"
logger.info(x)

val typeRef = object : TypeReference<LinkedHashMap<String, String>>() {}

val xParsed = objectMapper.readValue(x, typeRef)
if (xParsed["x"] == "ü") {
  logger.info("parsed ue correctly")
} else {
  logger.info("converted ue incorrect")
}

val xJ = Json.of(x)
val xConverted = objectMapper.readValue(xJ.asString(), typeRef)
logger.info(xConverted["x"])
if (xConverted["x"] == "ü") {
  logger.info("converted ue correctly")
} else {
  logger.info("converted ue incorrect")
}

当 IDE 中的 运行 时,它按预期工作。这是日志输出:

2021-08-11 14:21:16.237  INFO 25810 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : test
2021-08-11 14:21:16.237  INFO 25810 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : {"x": "ü"}
2021-08-11 14:21:16.237  INFO 25810 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : parsed ue correctly
2021-08-11 14:21:16.238  INFO 25810 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : ü
2021-08-11 14:21:16.238  INFO 25810 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : converted ue correctly

当我在使用 ./gradlew bootBuildImage 构建图像后从 docker 容器中 运行 时,容器的输出是:

backend_1  | 2021-08-11 12:25:28.905  INFO 9 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : test
backend_1  | 2021-08-11 12:25:28.905  INFO 9 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : {"x": "?"}
backend_1  | 2021-08-11 12:25:28.906  INFO 9 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : parsed ue correctly
backend_1  | 2021-08-11 12:25:28.906  INFO 9 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : ??
backend_1  | 2021-08-11 12:25:28.906  INFO 9 --- [tor-tcp-epoll-1] some.feature.serviceImpl      : converted ue incorrect

如日志所示,第一部分没问题,但在 Json 转换后变音变了。为什么以及如何解决这个问题?

原来将环境变量 JAVA_OPTS 设置为 -Dfile.encoding=UTF8 修复了它。但我仍然不明白为什么其他服务在不使用手动 json 转换的情况下工作正常。

例如在 docker-compose.yml

  my_service:
    image: the_image
    ports:
      - 8080:8080
    environment:
      JAVA_OPTS: "-Dfile.encoding=UTF8"