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

3

9

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)?

Cartridge answered 25/6, 2015 at 18:40 Comment(0)
N
8

To add to jst's answer, the Spring Boot annotation @ConfigurationPropertiesBinding can be used for Spring Boot to recognize the converter for property binding, as mentioned in the documentation under Properties Conversion:

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

  @Override
  public Path convert(String pathAsString) {
    return Paths.get(pathAsString);
  }
}
Nummulite answered 17/9, 2018 at 8:56 Comment(0)
R
6

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.

Randi answered 25/6, 2015 at 19:10 Comment(1)
I put this into a @Configuration class and made the Converter<String, Path> a bean (@Bean). That took care of registration using Spring BootCartridge
P
2

I took up james idea and defined the converter within the spring boot configuration:

@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();
    }
}
Polytechnic answered 28/3, 2019 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.