Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

java - 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}"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...