如何在运行时从输入字符串中读取spring中的属性文件值

时间:2017-06-19 13:36:33

标签: java xml spring properties spring-config

我在项目中使用Java + Spring + spring XML配置。

我想从属性文件中读取一个属性值,并使用输入String值在spring配置中设置java值。

MyClass.class

log_path=C:\test\app
table1_details=table1Name|table1Key|query1
table2_details=table2Name|table2Key|query2
table3_details=table3Name|table3Key|query3

myTest.properties

<bean id="myClass" class="com.test.MyClass">
        <property name="logpath" ref="${log_path}"/>
<property name="tableName" value="#{systemProperties['checker.table']}"/>        
        <property name="tabledetails" value="${#{systemProperties['checker.table']}}"/>

Spring_config.xml

<!--working-->
<property name="tableDetails" value="${table1_details}"/> 
<!--not working-->
<property name="tableDetails" value="${#{systemProperties['checker.table']}}"/> 

假设checker.table = table1_details然后

{{1}}

所以要求是我在systemProperties ['checker.table']中有属性名称,我无法在value字段中使用它来读取table1_details的属性详细信息并在MyClass中设置tableDetails?

2 个答案:

答案 0 :(得分:1)

在java / pojo类中从属性文件中获取值write -

@value("${table1_details}")
String tableDetails;

@value("${log_path}")
String logpath;

您还必须在xml中提及您的属性文件 -

<context:place-holder location="classpath*:myTest.properties">

在xml文件中读取POJO的值,调用get方法,如 -

<bean id="abc" class = "qwe.ert.MyClass"/> 
<bean id="xyz" class= "qwe.ert.NewClass">
    <property name="tableDetails" value="#{abc.getTableDetails()}">
    <property name="log" value="#{abc.getLogPath()}">
</bean>

答案 1 :(得分:0)

使用

为您的课程添加注释
@PropertySource("sourceOfProperty")

将值注入字段

@Value(${property})

您还可以从环境

访问属性
env.getProperty("property")
相关问题