How to inject java.nio.file.Path dependency using @ConfigurationProperties

时间:2015-06-25 18:40:08

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

I'm using Spring Boot and have the following Component class: @Component @ConfigurationProperties(prefix="file") public class FileManager { private Path localDirectory; public void setLocalDirectory(File localDirectory) { this.localDirectory = localDirectory.toPath(); } ... } And the following yaml properties file: file: localDirectory: /var/data/test I would like to remove the reference of java.io.File (of setLocalDirectory) by replacing with java.nio.file.Path. However, I receive a binding error when I do this. Is there way to bind the property to a Path (e.g. by using annotations)?

3 个答案:

答案 0 :(得分:3)

I don't know if there is a way with annotations, but you could add a Converter to your app. Marking it as a @Component with @ComponentScan enabled works, but you may have to play around with getting it properly registered with the ConversionService otherwise. @Component public class PathConverter implements Converter<String,Path>{ @Override public Path convert(String path) { return Paths.get(path); } When Spring sees you want a Path but it has a String (from your application.properties), it will lookup in its registry and find it knows how to do it.

答案 1 :(得分:2)

要添加到上述jst的答案中,Spring Boot批注 @ConfigurationPropertiesBinding 可用于Spring Boot来识别用于属性绑定的转换器,如24.7.4 Properties Conversion中所述:

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

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

答案 2 :(得分:0)

我采纳了james的想法,并在spring boot配置中定义了转换器:

@SpringBootConfiguration
public class Configuration {
    public class PathConverter implements Converter<String, Path> {

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

    @Bean
    @ConfigurationPropertiesBinding
    public PathConverter getStringToPathConverter() {
        return new PathConverter();
    }
}