How to externalize applicationContext and construct the ClassPathXmlApplicationContext object

56 Views Asked by At

I need to externalize by spring applicationContext configuration. I run my jar as :

java -jar myjar.jar --spring.config.location=file:///Users/nsarkar/temp/config/applicationContext.xml

How would spring understand this property and what do i have to set the ClassPathXmlApplicationContext constructor with?

Does spring know the location automatically since the names are predefined by spring? OR do we have to still pass the parameters taking from command line argument?

The following code isnt working.

public class RestaurantPromoCooking {


public static void main(String[] args) {

    ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext();
    CookFood cookFood = classPathXmlApplicationContext.getBean("promoItem", CookFood.class);
    cookFood.cookItem();
}

}

I need to externalize my config. Over the internet, all the suggestions were till using the property while running the jar and not beyond that.

Thanks in advance!!

1

There are 1 best solutions below

2
On

You can use custom property like this

java -DmyContextLocation=/home/myuser/context.xml -jar myjar.jar

And then in the code do the following:

FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + System.getProperty("myContextLocation");