Java 以注释方式读取属性文件而不使用Spring的任何API
我在应用程序中未使用Spring。是否有API可以基于注释将属性文件加载到JavaPOJO中。 我知道使用InputStream或Spring的PropertyPlaceHolder加载属性文件。 有什么API可以用来填充我的pojo吗Java 以注释方式读取属性文件而不使用Spring的任何API,java,spring,reflection,properties,annotations,Java,Spring,Reflection,Properties,Annotations,我在应用程序中未使用Spring。是否有API可以基于注释将属性文件加载到JavaPOJO中。 我知道使用InputStream或Spring的PropertyPlaceHolder加载属性文件。 有什么API可以用来填充我的pojo吗 @Value("{foo.somevar}") private String someVariable; 如果不使用spring,我无法找到任何解决方案。我想出了一个快速的方法来绑定属性,如下所示 注意:未对其进行优化,未处理错误。仅显示一种可能性。 @Ret
@Value("{foo.somevar}")
private String someVariable;
如果不使用spring,我无法找到任何解决方案。我想出了一个快速的方法来绑定属性,如下所示 注意:未对其进行优化,未处理错误。仅显示一种可能性。
@Retention(RetentionPolicy.RUNTIME)
@interface Bind
{
String value();
}
我已经测试了它的一些基本参数,正在工作
class App
{
@Bind("msg10")
private String msg1;
@Bind("msg11")
private String msg2;
//setters & getters
}
public class PropertyBinder
{
public static void main(String[] args) throws IOException, IllegalAccessException
{
Properties props = new Properties();
InputStream stream = PropertyBinder.class.getResourceAsStream("/app.properties");
props.load(stream);
System.out.println(props);
App app = new App();
bindProperties(props, app);
System.out.println("Msg1="+app.getMsg1());
System.out.println("Msg2="+app.getMsg2());
}
static void bindProperties(Properties props, Object object) throws IllegalAccessException
{
for(Field field : object.getClass().getDeclaredFields())
{
if (field.isAnnotationPresent(Bind.class))
{
Bind bind = field.getAnnotation(Bind.class);
String value = bind.value();
String propValue = props.getProperty(value);
System.out.println(field.getName()+":"+value+":"+propValue);
field.setAccessible(true);
field.set(object, propValue);
}
}
}
}
在根类路径中创建app.properties
msg10=message1
msg11=message2
.properties
文件?您是否尝试过ResourceBundle
?不过,它不会像你尝试的那样起作用。你可以自己写。使用反射API。@MdFaraz是的,这就是我现在正在做的事情,但是如果有一个经过验证的API,它的使用价值将得到更好的特性测试。如果spring做了你想做的事情,而你不想自己写,为什么不使用spring呢?@azurefrog正如我使用spring一样,这意味着整个DI和JVM中的其他核心框架。我不需要任何Spring特有的特性