Java Spring-基于application.properties中的值加载自定义属性文件

Java Spring-基于application.properties中的值加载自定义属性文件,java,spring,Java,Spring,我有application.properties文件: value=a 然后我想基于该值加载属性文件-a.properties,并从该文件读取/使用属性 我在想这样的事情: @Configuration public class PropertiesConfiguration { @Value("${value}") private String value; @Bean public PropertySourcesPlaceholderConfigurer placeHolderConf

我有application.properties文件:

value=a
然后我想基于该值加载属性文件-a.properties,并从该文件读取/使用属性

我在想这样的事情:

@Configuration
public class PropertiesConfiguration {

@Value("${value}")
private String value;

@Bean
public PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocation(new ClassPathResource(value + ".properties"));
    return configurer;
} }

但是由于某种原因,值始终为空。当我尝试获得该值时,例如在服务/组件中,它工作正常。我希望避免使用spring配置文件。你知道如何用最新的Spring实现这一点吗?

configurer.setLocation(新的类路径资源(value+“.properties”))一行中
它应该是
“application.properties”
,因为您的文件名是
application.properties

另外,在属性文件中,将其定义为
value=a

使用空格时,我遇到的一个解决方案是使用组件和PropertySource注释,这个解决方案效果很好

@Component
@PropertySource(value = "classpath:${value}.properties")
public class CountryService implements ICountryService {

@Value("${<whatever in a.properties file>}")
private String currency;

@Override
public String getCurrency() {
    return currency;
}
}
@组件
@PropertySource(value=“classpath:${value}.properties”)
公共类CountryService实现ICountryService{
@值(“${}”)
私人字符串货币;
@凌驾
公共字符串getCurrency(){
返回货币;
}
}

其中,${value}取自application.properties。然后在需要时自动连接该bean。

我可能错了,但这听起来像是X/Y问题。如果您试图拥有多个不同的属性文件,并且作为开发人员能够在它们之间切换,那么您可能需要的是Spring概要文件。如果没有更多关于您正试图解决的确切问题的信息,很难说。这里有一篇文章你可能会觉得很有帮助:@kashishverma假设a.properties只包含一个值country=en。因此,稍后我想在一些组件中以值(${country})的形式访问它,由于两个原因,它显然不起作用。首先,
属性资源占位符配置器
是处理
@值
注释的组件。第二,在加载/替换属性时只有一个过程,在所有问题都解决之前没有多个过程。@M.Deinum有什么解决方案吗?我在想第一部分有道理。我现在的解决方法是@Bean@ConditionalOnProperty(name=“value”,havingValue=“a”)公共属性资源占位符配置器占位符配置器(){…//加载正确的属性文件,该文件可用于应用程序。属性直接放在类路径的资源文件夹中,以便正确加载(我可以从组件/服务中读取值)。空格应该在其中发挥作用。