realsim
realsim

Reputation: 1640

Spring properties that depend on other properties

I would like to have properties, that I can reference via @Value in spring beans, that can only be created dependend on other properties. In particular I am having a property, that describes the file system location of a directory.

myDir=/path/to/mydir

And by convention, there is a file in that directory, that is always called myfile.txt.

Now i want to have access to both, the directory and the file, via @Value annotations inside my beans. And sometimes I want to access them as Strings, sometimes as java.io.Files and sometimes as org.springframework.core.io.FileSystemResource (which by the way works very well out of the box!). But because of that concatenating Strings on demand is not an option.

So what I of course could do is just declare both, but I would end up with

myDir=/path/to/mydir
myFile/path/to/mydir/myfile.txt

and I would like to avoid that.

So I came up with an @Configuration class, that takes the property and adds it as new PropertySource:

@Autowired
private ConfigurableEnvironment environment;

@Value("${myDir}")
private void addCompleteFilenameAsProperty(Path myDir) {
    Path absoluteFilePath = myDir.resolve("myfile.txt");

    Map<String, Object> props = new HashMap<>();
    props.put("myFile, absoluteFilePath.toString());
    environment.getPropertySources().addFirst(new MapPropertySource("additional", props));
}

As you can see, in my context I even created a PropertyEditor, that can convert to java.nio.file.Paths.

Now the problem is, that for some reason, this "works on my machine" (in my IDE), but does not run on the intended target environment. There I get

java.lang.IllegalArgumentException: Could not resolve placeholder 'myFile' in string value "${myFile}"

Upvotes: 54

Views: 57781

Answers (2)

Sanjay Bharwani
Sanjay Bharwani

Reputation: 4779

Spring expressions can be used to refer the properties.

In my example it was

query-parm=QueryParam1=
query-value=MyParamaterValue

Now while binding them in Spring Bean.

 @Configuration
    public class MyConfig {
    @Value("${query-param}${query-value}")
    private String queryString;
 }

Above code will inject QueryParam1=MyParamaterValue to the variable queryString.

Upvotes: 1

Sylvain Deschenes
Sylvain Deschenes

Reputation: 1236

Spring can combine properties

myDir=/path/to/mydir 
myFile=${myDir}/myfile.txt

You can also use a default value without defining your myFile in the properties at first:

Properties file

myDir=/path/to/mydir

In class:

@Value("#{myFile:${myDir}/myfile.txt}")
private String myFileName;

Upvotes: 107

Related Questions