Loading properties file from WEB-INF folder in a l

2019-07-24 15:19发布

问题:

We're writing a custom log4j appender for our application. The appender should log its events to a database. Now the problem I'm having is setting up the database connection. Our jdbc settings are in a file called jdbc.properties which is located directly under the WEB-INF folder.

I've tried accessing the properties file using the following code

InputStream stream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("jdbc.properties");

... but stream results in being null. Any ideas how I can load a properties file from the WEB-INF folder in a log4j appender without moving the properties file to another location?

回答1:

May be you can try,

 String  path =Thread.currentThread().getContextClassLoader().getResource("/").toURI().resolve("../jdbc.properties").getPath();
 Properties ps=new Properties();
 ps.load(new FileInputStream(path));


回答2:

You should be able to get the file via the ServletContext. i.e.:

ServletContext ctx = ...
InputStream stream = ctx.getResourceAsStream("/WEB-INF/jdbc.properties"); 

Okay, just saw, that you don't have access to the ServletContext - forget the answer.

Isn't it possible to add the information for the jdbc connection into the log4j.properties? Why are you seperating the two?