【发布时间】:2022-01-24 10:09:00
【问题描述】:
我正在将我的 java 应用程序从 Spring 迁移到 Spring Boot,并且我想消除基于 xml 的配置并完全迁移到 基于注释的配置。 p>
我想将属性文件按原样加载到 java.util.Properties 类型变量中。
@Configuration
public class ApplicationConfig
{
// inject the file into this variable
private Properties myOtherProp;
}
在基于 xml 的配置中,这是通过以下方式在一行中完成的:
<util:properties id="myOtherProp" location="classpath:myOtherProperties.properties"/>
我目前实现这一目标的方式是这样做:
@Configuration
public class ApplicationConfig
{
private Properties myOtherProp;
private void myMethodToInitialiseMyOtherProp()
{
myOtherProp = new Properties();
myOtherProp.load(getClass().getClassLoader().getResourceAsStream("myOtherProperties.properties"));
}
@Bean
public myClass beanWhichUsesTheOtherProp()
{
myMethodToInitialiseMyOtherProp();
return new myClass(myOtherProp);
}
}
我正在寻找一种解决方案来在一行中执行此操作,就像 @Value 对原始数据类型所做的那样。
或者至少能够调用我的方法 - myMethodToInitialiseMyOtherProp(),我在其中声明了 Properties 变量,这样我就可以消除在任何地方第一次使用它之前记住调用函数来初始化变量的开销。
我知道如何注入在 myOtherProperties.properties 中声明的各个字段,但这不是我想要在这里实现的。我希望将整个文件加载到变量中 - 类型为属性的 myOtherProp。
类似这样的:
@Configuration
public class ApplicationConfig
{
// inject the file into this variable
@Something-Like-Value-Annotation-To-Inject-The-File-In-One-Line
// OR //
@Some-Way-To-Call-myMethodToInitialiseMyOtherProp()
private Properties myOtherProp;
}
【问题讨论】:
标签: java spring spring-boot spring-annotations