【问题标题】:user input arguments to be passed to spring application context要传递给 Spring 应用程序上下文的用户输入参数
【发布时间】:2014-08-24 02:51:52
【问题描述】:

我有一个 Java 应用程序,它接受配置文件路径的用户输入。我希望将此输入配置文件路径传递给我的 spring applicationContext.xml,以便我可以使用 dburl、dbusername 和dbpasswd 将在我的应用程序的其他类中使用。

有没有办法将运行时用户参数传递给 Spring 应用程序上下文?如果是,那么如何在 applicationContext.xml 中检索它

【问题讨论】:

    标签: java spring main


    【解决方案1】:

    您基本上有三种方法可以让您的应用程序上下文了解运行时配置:

    • 使用属性文件和PropertyPlaceholderConfigurer - 可以正常工作,但您必须使用磁盘文件来传递内存中已经存在的数据
    • 使用系统属性,因为PropertyPlaceholderConfigurer 可以将它们用作属性文件的后备(或首选) - 不使用磁盘,但您必须正确选择属性名称以避免副作用(通常前缀必须在您的自己的命名空间)
    • 在专用类甚至 bean 中使用静态字段 - 不一定很好,但 它可以工作

    当然,无论您选择何种方法,请务必在应用程序上下文刷新和启动之前初始化这些数据。

    【讨论】:

    • 感谢 serge 我正在使用 PropertySourcesPlaceholderConfigurer 从我的磁盘中获取属性文件资源,但问题在于 applicationContext.xml 如何在设置 bean“${db.driverClass}”时检索属性确实不工作:(
    • 它应该可以工作...请显示您的PropertySourcesPlaceholderConfigurer 配置和属性文件的结构。
    • 这是我在调用 main() GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context); xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml")); PropertySourcesPlaceholderConfigurer propReader = new PropertySourcesPlaceholderConfigurer(); propReader.setLocation(new ClassPathResource(config)); context.refresh();
    • 我的属性看起来像这样 db.url=jdbc:oracle:thin:@147.128.72.91:1528/PC db.driverClass=oracle.jdbc.driver.OracleDriver db.username=orausr db。密码=orapwd
    • 我不知道是否可以在ApplicationContext 之外配置PropertySourcesPlaceholderConfigurer 我总是在xml 文件中将它们声明为<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations" value="classpath:config"/></bean>
    【解决方案2】:

    创建一个保存运行时数据的类,在 applicationContext.xml 中将其声明为 Bean,然后在数据源的属性中提供该类的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-24
      • 2020-12-15
      • 2023-03-26
      • 1970-01-01
      • 2011-10-18
      • 2021-01-10
      • 1970-01-01
      相关资源
      最近更新 更多