Reading a “properties” file

2019-08-20 10:14发布

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

2条回答
祖国的老花朵
2楼-- · 2019-08-20 10:53

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>
查看更多
再贱就再见
3楼-- · 2019-08-20 11:09

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?

查看更多
登录 后发表回答