如何将applicationContext外部化并构建ClassPathXmlApplicationContext对象。

huangapple go评论57阅读模式
英文:

How to externalize applicationContext and construct the ClassPathXmlApplicationContext object

问题

我需要将Spring的应用程序上下文配置外部化。
我以以下方式运行我的jar包:

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

Spring如何理解这个属性,我需要如何设置ClassPathXmlApplicationContext构造函数?

Spring是否会自动识别这个位置,因为这些名称是由Spring预定义的?还是我们仍然需要从命令行参数中传递这些参数?

以下代码无法正常工作。

    public class RestaurantPromoCooking {


    public static void main(String[] args) {

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


}

我需要将配置外部化。在互联网上,所有的建议都是在运行jar包时使用属性,而不超出这个范围。

提前感谢!
英文:

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

得分: 1

你可以像这样使用自定义属性:

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

然后在代码中进行以下操作:

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

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");

huangapple
  • 本文由 发表于 2020年9月8日 09:12:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63785905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定