【问题标题】:how to read property file value in spring at runtime from input string如何在运行时从输入字符串中读取spring中的属性文件值
【发布时间】:2017-06-19 13:36:33
【问题描述】:

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

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

MyClass.class

private String tableDetails;
private String logpath;

myTest.properties

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

Spring_config.xml

<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']}}"/>

然后假设 checker.table = table1_details

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

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

【问题讨论】:

    标签: java xml spring properties spring-config


    【解决方案1】:

    在您的 java/pojo 类中从属性文件中获取值写入 -

    @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>
    

    【讨论】:

      【解决方案2】:

      注释你的类
      @PropertySource("sourceOfProperty")
      

      向字段注入值

      @Value(${property})
      

      您还可以从环境中访问属性

      env.getProperty("property")
      

      【讨论】:

        猜你喜欢
        • 2017-03-05
        • 2014-03-03
        • 2011-08-05
        • 1970-01-01
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多