简体   繁体   中英

Java jvm options override property inside property file

I am using java with spring.

I have stand alone application having property file contains database connection url.

Due to some reason if I want to override one property I see some where we can override property by passing property and its value by passing it as jvm options.

java -Dcom.abc.project.model.jdbc.ConnectionUrl=jdbc:jtds:sqlserver://abc-al01.abc.com/model_QA [executeablejar] myjavafile

Can some one explain how does it work ?

So you want to load some db-related data from a properties file but you want to implement a functionality that overrides that data with a System Property data, why can't you do something like this?

Properties prop = new Properties();

try {
    prop.load(new FileInputStream("config.properties"));

    String connUrl = prop.getProperty("com.abc.project.model.jdbc.ConnectionUrl");
    String theOtherConnUrl = System.getProperty("com.abc.project.model.jdbc.ConnectionUrl");

    if(theOtherConnUrl!=null){
        connUrl = theOtherConnUrl;
           ...

I believe the override behavior will depend on the way you implement the code that is going to retrieve this data from both the properties file and the System Property, why not leaving all the DB-related data inside a single properties file (with multiple connection data separate by different parameters names, eg, jdbc.sqlserver.host & jdbc.oracle.host) and use a flag to identify which data you want to use (you can place this flag in a System Property, eg, -Dcom.abc.project.model.jdbc.db=sqlserver).

in 1行:String connUrl = System.getProperty(“com.abc.project.model.jdbc.ConnectionUrl”,prop.getProperty(“com.abc.project.model.jdbc.ConnectionUrl”));

Here is a basic example

context.xml

<context:property-placeholder location="/test.properties" system-properties-mode="OVERRIDE"/> 
<bean class="Test">
    <property name="xxx" value="${xxx}" />
</bean>

test.properties

xxx=1

Test.java

public class Test {

    public void setXxx(String xxx) {
        System.out.println(xxx);
    }

    public static void main(String[] args) throws Exception {
        new ClassPathXmlApplicationContext("context.xml");
    }
}

Initially Test prints the value from test.properties - 1 . But if you run Test with -Dxxx=2 it prints 2 . That is system property overrides property from the file

see this.. it solves the problem with spring config itself.. no need to change the code

Spring placeholder format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM