1

我一直在假设一些东西,现在发现它是不正确的。我的 spring 上下文中有以下配置属性声明:

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="searchContextAttributes" value="true" />
        <property name="contextOverride" value="true" />
        <property name="locations">
            <list>
                <value>classpath:/app.properties</value>
            </list>
        </property>
    </bean>

我认为 from 的值app.properties会覆盖我的系统属性,所以我可以像这样在我的 Java 类中直接访问它们:

String someThingFromPropertyFile = System.getProperty("nameFromPropertyFile");

当然,我到处都是空指针异常。现在我在这里询问如何从您的应用程序(您的应用程序的 Java 类的一部分)访问您的应用程序属性。

有没有比下面更好的方法(我不是说它不好)。

使用 Spring 以编程方式访问属性文件?

4

2 回答 2

6

在应用程序上下文中:

 <context:property-placeholder location="classpath:your.properties" ignore-unresolvable="true"/>

然后在java中你可以这样做:

@Value("${cities}")
private String cities;

your.properties 包含以下内容:

cities = my test string 
于 2012-10-09T15:51:52.613 回答
0

Spring properties do not override System properties. It works the other way. You should be getting all your properties from Spring and not from System.getProperties(). System properties will override Spring properties with the same name. The SYSTEM_PROPERTIES_MODE_OVERRIDE you are setting says that when you get a property value from Spring the System property will win.

You want to set the value to be SYSTEM_PROPERTIES_MODE_FALLBACK. This is the default so you don't actually need to set it.

If you have this in mind, @NimChimpsky has it the correct method for accessing property values:

@Value("${nameFromPropertyFileOrSystemProperty}")
private String someThingFromProperty;
于 2012-10-09T16:40:55.503 回答