Reading a “properties” file

佐手、 提交于 2019-12-13 07:16:38

问题


I have a Rest service using Resteasy (running on top of Appengine), with the following psuedo code:

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

However its obvious that the servlet context cannot be accessed here.

And code like:

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

Can't be executed within the Appengine environment.

EDIT:

I have tried doing it with Spring like:

appContext.xml

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

Then, put this on the actual class fields:

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

However, part of the code of the MyService complains because the username and password was not "injected", I mean its empty although its on the auth.properties file


回答1:


In RESTEasy you can easily inject Servlet context via @Context annotation: http://docs.jboss.org/resteasy/docs/2.3.1.GA/userguide/html_single/index.html#_Context

Examples can be found here: Rest easy and init params - how to access?




回答2:


This should work if you put the file in /WEB-INF/classes/ (which, importantly, is on the classpath), specifying config.properties as a file at the top-level.

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

See this similar question: How to load properties file in Google App Engine?

Edit: Now you've edited, I'll respond & answer the Spring-related question. So, put the auth.properties into /WEB-INF/classes/ , and then specify classpath as follows.

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


来源:https://stackoverflow.com/questions/10379887/reading-a-properties-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!