2012-08-07 57 views
5

我想编写一个弹簧命令行程序,该程序使用作为命令行参数传递的属性文件进行初始化。如何做到这一点?从命令行加载弹簧上下文属性

启动类:

public static void main (String [] args) { 
    String configFilename = args[0]; 
    ApplicationContext ctx = new ClassPathXmlApplicationContext(
     "classpath:/context/applicationContext.xml"); 
    MyBean bean = ctx.getBean(MyBean.class); 
    bean.getStarted(); 
} 

的applicationContext.xml:

<context:property-placeholder location="CONFIGFILENAME" ignore-unresolvable="true"/> 

如何获取配置文件名了从我的主要方法,以实际Spring上下文,这样我可以加载正确的环境依赖属性?

+2

您可以使用JVM参数代替: http://stackoverflow.com/questions/5598217/how-do-i-read-jvm-arguments-in-the-spring-applicationcontext-xml – DB5 2012-08-07 09:42:17

回答

6

在你的情况,你可以更好地设置属性文件位置的系统属性

System.getProperties().setProperty("location", args[0]); 

然后在applicationContext.xml文件

<context:property-placeholder location="${location}" ignore-unresolvable="true"/> 

希望这将解决您的问题。