且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java Webapp和java普通应用程序中读取公共外部属性文件

更新时间:2023-09-06 09:30:34

您可以将< context> 添加到tomcat / conf / server.xml(在此示例中为linux路径):

 < Context docBase =/ home / yourusername / tomcat / assestspath =/ assets/> 

如果您使用的是Windows:

 < Context docBase =C:\ path\to\myapp\assetspath =/ assets/> 

然后您可以像访问webapp中的任何其他资源一样访问它(例如:/ assets / myappConfig。例如,如果您使用JDBC,则可以将连接属性存储在Singleton中并从那里请求它,并且该类可以处理更改检查在该文件上。


I know this question has answered many a time with most useful answer as below,

Where to place and how to read configuration resource files in servlet based application?

However, We have some special requirement as below,

  1. Webapp will be deployed to tomcat.
  2. Normal java app in form of .jar will be placed under folder /myapp
  3. myappConfig.property file will be placed under /myapp

Directory Structure on client machine

/myapp
   /myapp.jar
   /assests/myappConfig.property
   /tomcat/webapps/myapp.war

Basically myapp.jar and myapp.war will access sql db connection values for MySql database connection and db operations.

Accessing myappConfig.property from myapp.jar --> Working fine

        File jarPath = new File(Myapp.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath = jarPath.getParent();
        System.out.println(" propertiesPath-" + propertiesPath);
        mainProperties.load(new FileInputStream(propertiesPath + "\\assets\\myapp.property"));

Can anyone help/suggest how to implement,

Accessing myappConfig.property file from mywebapp,

provided run time change in myappConfig.property file does not required myapp.war to be redeployed

Thanks for your help in advance.

edit

Below is the steps in which we want to deliver the project to client.

  1. Below is my app directory

    /myapp
      /myapp.jar
      /assests/myappConfig.property
      /tomcat/webapps/myapp.war
    

  2. pack everything in one package with some packaging tool.

  3. Run this package in client machine at any location and it will have same directory structure as above

  4. Here, I do not want to hard code any location in webapp or tomcat for "/assests/myappConfig.property"

  5. Normal Java app I can read property file but for wepapp I am not getting clear idea for how to do that?

You can add a <context> to tomcat/conf/server.xml (in this example, linux path):

<Context docBase="/home/yourusername/tomcat/assests" path="/assets" />

If you are using Windows:

<Context docBase="C:\path\to\myapp\assets" path="/assets" />

And then you can access it like any other resource within your webapp (e.g.: /assets/myappConfig.property).

If you are using JDBC for example, you could store the connection properties in a Singleton and request it from there, and that class could take care of change checks on that file.