使用springframeworkjava读取动态键值对
上述值位于test.properties的属性文件中 我能够打印键A1_M1的X1值,如下代码所示 如果我的键值是动态的,我不知道(属性文件的)键,直到我处理另一个被发送到类的papratmer的对象,我需要一些如何实现它的指导。我需要处理这个对象以了解密钥,然后查看属性文件以确定密钥是否存在。如果存在,则返回值,否则返回默认值使用springframeworkjava读取动态键值对,java,spring,Java,Spring,上述值位于test.properties的属性文件中 我能够打印键A1_M1的X1值,如下代码所示 如果我的键值是动态的,我不知道(属性文件的)键,直到我处理另一个被发送到类的papratmer的对象,我需要一些如何实现它的指导。我需要处理这个对象以了解密钥,然后查看属性文件以确定密钥是否存在。如果存在,则返回值,否则返回默认值 A1_M1=X1 A1_M2=X2 A1_M3=X3 A2_M1=X4 Default=X5 使用下面的代码将属性放入对象中,稍后可以使用getPropert
A1_M1=X1
A1_M2=X2
A1_M3=X3
A2_M1=X4
Default=X5
使用下面的代码将属性放入对象中,稍后可以使用
getProperty()
方法检查属性值是否存在。如果不返回getProperty(“默认值”)
:
您可以使用带有默认值的@Value注释
@Resource(name = "nodeProperty")
private Properties nodeProperty;
谢谢,能够处理数据。很高兴知道它起作用了!你可以接受答案D
SpringDemo.java
package com.jpmc.selftutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
@Component("SpringDemo")
public class SpringDemo {
private static String a1m1;
@Autowired
public SpringDemo(@Value("${A1_M1}") String a1m1){
SpringDemo.a1m1 = a1m1;
}
@SuppressWarnings({ "resource", "unused" })
public static void main(String args[]){
ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext(new String[]
{ "spring-bean.xml" });
System.out.println("Value of a1m1: " +a1m1);
}
}
@Resource(name = "nodeProperty")
private Properties nodeProperty;
@Value("#{nodeProperty['A1_M1'] ?: nodeProperty['Default']}")