依赖于其他属性的弹簧属性 [英] Spring properties that depend on other properties

查看:67
本文介绍了依赖于其他属性的弹簧属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一些属性,这些属性可以在spring bean中通过@Value引用,只能依赖于其他属性来创建.特别是我拥有一个属性,该属性描述目录的文件系统位置.

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

按照约定,该目录中有一个文件,始终称为 myfile.txt .

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

现在,我想通过我的bean内的@Value注释访问目录和文件.有时我想以String形式访问它们,有时以java.io.Files形式访问它们,有时以org.springframework.core.io.FileSystemResource形式访问它们(顺便说一句,开箱即用!).但是由于这个原因,按需连接字符串不是一个选择.

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

我想避免这种情况.

所以我想出了一个@Configuration类,该类接受属性并将其添加为新的PropertySource:

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));
}

如您所见,在我的上下文中,我什至创建了一个PropertyEditor,它可以转换为 java.nio.file.Path s.

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

现在的问题是,由于某种原因,它可以在我的机器上工作"(在我的IDE中),但是不能在预期的目标环境上运行.我知道了

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}"

推荐答案

Spring可以合并属性

Spring can combine properties

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

您也可以使用默认值,而无需首先在属性中定义 myFile :

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

属性文件

myDir=/path/to/mydir

在课堂上:

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

这篇关于依赖于其他属性的弹簧属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆