【问题标题】:Properties framework in java appsJava 应用程序中的属性框架
【发布时间】:2011-02-06 22:58:55
【问题描述】:

我一直使用spring 作为我的 IOC。它还有一种很好的方式在你的 bean 中注入属性。

现在我正在参与一个 IOC 为 Guice 的新项目。我不完全理解我应该如何使用 Guice 将属性注入到我的 bean 中的概念。

问题:是否真的可以将原始属性(字符串、整数)注入到我的 guice bean 中。如果答案是否定的,那么也许您知道一些不错的 Java 属性框架。 因为现在我想在我的应用程序中使用ResourceBundle 类进行简单的属性管理。但是在使用 spring 一段时间后,这对我来说似乎还不够。

【问题讨论】:

    标签: java spring guice


    【解决方案1】:

    this SO post 讨论了各种配置框架的使用,以及属性的使用。我不确定它是否完全符合您的需求,但也许您可以在那里找到一些有价值的东西。

    【讨论】:

      【解决方案2】:

      Spring 提供了对 XML 文件中的配置信息的注入。我不希望安装我的软件的人必须编辑 XML 文件,因此对于纯文本文件中更合适的配置信息(例如路径信息),我已经回到使用 java.util.Properties因为它很容易使用并且非常适合 Spring,如果你使用 ClassPathResource,它允许文件本身的无路径位置(它只需要在类路径中;我把我的放在 WEB-INF/classes 的根目录下) .

      这是一个返回填充的 Properties 对象的快速方法:

      /**
       *  Load the Properties based on the property file specified 
       *  by <tt>filename</tt>, which must exist on the classpath
       *  (e.g., "myapp-config.properties").
       */
      public Properties loadPropertiesFromClassPath( String filename )
              throws IOException
      {
          Properties properties = new Properties();
          if ( filename != null ) {
              Resource rsrc = new ClassPathResource(filename);
              log.info("loading properties from filename " + rsrc.getFilename() ); 
              InputStream in = rsrc.getInputStream();
              log.info( properties.size() + " properties prior to load" ); 
              properties.load(in);
              log.info( properties.size() + " properties after load" );         
          }
          return properties;
      }
      

      文件本身使用普通的“name=value”纯文本格式,但如果您想使用 Properties 的 XML 格式,只需将 properties.load(InputStream) 更改为 properties.loadFromXML(InputStream)。 希望对您有所帮助。

      【讨论】:

      • 我想你误解了我的问题,但感谢代码和答案。
      【解决方案3】:

      在 Guice 中注入属性很容易。在从文件中读取某些属性之后,或者使用Names.bindProperties(Binder,Properties) 绑定它们。然后,您可以使用 @Named("some.port") int port 等方式注入它们。

      【讨论】:

        猜你喜欢
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        相关资源
        最近更新 更多