【问题标题】:Reading a "properties" file读取“属性”文件
【发布时间】:2012-04-30 07:19:04
【问题描述】:

我有一个使用 Resteasy(在 Appengine 之上运行)的 Rest 服务,其伪代码如下:

@Path("/service")
public class MyService {
  @GET
  @Path("/start")
  public Response startService() {
     // Need to read properties file here.
     // like: servletContext.getResourceAsStream("/WEB-INF/config.properties")
  }
}

但是很明显这里不能访问 servlet 上下文。

代码如下:

 InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("/WEB-INF/config.properties");  

无法在 Appengine 环境中执行。

编辑:

我试过用 Spring 来做:

appContext.xml

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="/WEB-INF/auth.properties"/>
</bean>

然后,将其放在实际的类字段中:

@Path("/service")
public MyService{
    @Autowired
    @Value("${myservice.userid}")
    private String username;
    @Autowired
    @Value("${myservice.passwd}")
    private String password;
 // Code omitted
}

但是,MyService 的部分代码抱怨因为 usernamepassword 没有“注入”,我的意思是它是空的,尽管它在 auth.properties 文件中

【问题讨论】:

    标签: spring google-app-engine rest resteasy


    【解决方案1】:

    在 RESTEasy 中,您可以通过@Context 注解轻松注入 Servlet 上下文:http://docs.jboss.org/resteasy/docs/2.3.1.GA/userguide/html_single/index.html#_Context

    可以在此处找到示例:Rest easy and init params - how to access?

    【讨论】:

      【解决方案2】:

      如果您将文件放入/WEB-INF/classes/(重要的是,它位于类路径中),这应该可以工作,并将 config.properties 指定为*文件。

      this.getClass().getClassLoader().getResourceAsStream("/config.properties");
      

      看到这个类似的问题:How to load properties file in Google App Engine?

      编辑:现在你已经编辑好了,我会回复并回答与 Spring 相关的问题。因此,将 auth.properties 放入 /WEB-INF/classes/ ,然后指定类路径如下。

      <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="location" value="classpath:auth.properties"/>
      </bean>
      

      【讨论】:

      • 不能把属性文件放到WEB-INF文件夹里?
      • 不,不使用那个方法,因为 WEB-INF 不在类路径上。该方法getResourceAsStream(..) 在类路径中查找。如果您不知道如何将它放入您的类路径,您可以随时将它放在您的源文件夹中,然后让javac 为您发送它。
      • 同样的问题,用户名和密码没有注入
      • hmm,一些疯狂的猜测:你的 Spring 配置中有 吗?如果你不这样做,它可能不会处理注释。或者,属性处理可能在到达正确点之前就失败了。这似乎是一个 Spring 问题 - 建议您用更多信息将您的问题改写为一个新问题。自从我第一次回答以来,范围发生了很大变化!祝你好运