Java: Accessing properties file inside a war

后端 未结 6 1457
花落未央
花落未央 2020-12-06 06:29

I already searched StackOverflow for \"properties inside war\", but none of the results worked for my case.

I am using Eclipse Galileo and GlassFish v3 to develop a

相关标签:
6条回答
  • 2020-12-06 07:01
    Properties props = new Properties();
    props.load(this.getClass().getResourceAsStream("/com/company/config/file.properties"));
    

    works when I'm in debug mode. I can see the values in the debugger, but I get a NullPointerException right after executing the "props.load" line and before going into the light below it.

    That's a different issue. At least now I know this is the way to access the config file.

    Thank you for your help.

    0 讨论(0)
  • 2020-12-06 07:06

    Since you are using Spring, then use the Resource support in Spring to inject the properties files directly.

    see http://static.springsource.org/spring/docs/3.0.x/reference/resources.html

    Even if the class that requires the properties file is not Spring managed, you can still get access to the ApplicationContext and use it to load the resource

    resource would be something like, classpath:settings.properties, presuming that your properties file got picked up by your build and dropped in the war file.

    You can also inject directly, from the docs:

    <property name="template" value="classpath:some/resource/path/myTemplate.txt">
    
    0 讨论(0)
  • 2020-12-06 07:11

    Check the location of the properties file in WAR file. If it is in WEB-INF/classes directory under com/company/config directory getResourceAsStream("com/company/config/configfile.properties") should work or getResourceAsStream(" This should work if the config file is not under WEB-INF/classes directoy

    Also try using getClass().getClassLoader().getResourceAsStream.

    0 讨论(0)
  • 2020-12-06 07:14

    What is the path once it is deployed to the server? It's possible to use Scanner to manually read in the resource. From a java file within a package, creating a new File("../applications/") will get you a file pointed at {glassfish install}\domains\{domain name}\applications. Maybe you could alter that file path to direct you to where you need to go?

    0 讨论(0)
  • 2020-12-06 07:16

    Are you sure the file is being included in your war file? A lot of times, the war build process will filter out non .class files.

    0 讨论(0)
  • 2020-12-06 07:21

    If you are in a war, your classpath "current directory" is "WEB-INF/classes". Simply go up two levels.

    getResourceAsStream("../../com/company/config/configfile.properties");
    

    It is horrible but it works. At least, it works under tomcat, jboss and geronimo and It works today.

    P.S. Your directory structure is not very clear. Perhaps it is:

    getResourceAsStream("../../com.company.config/configfile.properties");
    
    0 讨论(0)
提交回复
热议问题