spring - 如何使用 @ConfigurationProperties 注入(inject) java.nio.file.Path 依赖项

标签 spring spring-boot properties-file java.nio.file

我正在使用 Spring Boot 并具有以下 Component 类:

@Component
@ConfigurationProperties(prefix="file")
public class FileManager {

    private Path localDirectory;

    public void setLocalDirectory(File localDirectory) {
        this.localDirectory = localDirectory.toPath();
    }

...

}

以及以下 yaml 属性文件:
file:
     localDirectory: /var/data/test

我想通过替换为 java.nio.file.Path 来删除 java.io.File (of setLocalDirectory) 的引用。但是,执行此操作时会收到绑定(bind)错误。有没有办法将属性绑定(bind)到路径(例如通过使用注释)?

最佳答案

要添加到上面 jst 的答案,Spring Boot 注释 @ConfigurationPropertiesBinding 可用于 Spring Boot 识别用于属性绑定(bind)的转换器,如 Properties Conversion 下的文档中所述:

@Component
@ConfigurationPropertiesBinding
public class StringToPathConverter implements Converter<String, Path> {

  @Override
  public Path convert(String pathAsString) {
    return Paths.get(pathAsString);
  }
}

关于spring - 如何使用 @ConfigurationProperties 注入(inject) java.nio.file.Path 依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31058245/

相关文章:

java - 我如何使用 highchart 在 jsp 中的 spring mvc 中绘制图形

java - Tomcat + Spring 和环境变量

Java无法上传带有@Pathvariable可选的文件

java - 如果 http 请求的内容类型是 urlencoded,如何让 Spring Boot Controller 读取对对象的 http 请求正文?

java - 在区域设置 'email.subject' 的代码 'en_US' 下找不到消息

java - Redis 集群与 Spring Boot 集成

java - 错误 :(229, 12) java : exception org. springframework.web.client.HttpStatusCodeException 已被捕获

java - COMM API安装错误: nblibraries.属性文件不存在

java - 如何为自定义 Quarkus ConfigProperties 使用配置映射

java - 如何将另一个属性文件中的值注入(inject)到 ValidationMessages.properties 中?