【问题标题】:How to access jdbc properties file (for Spring Security configuration) which is outside WEB-INF folder?如何访问 WEB-INF 文件夹之外的 jdbc 属性文件(用于 Spring Security 配置)?
【发布时间】:2015-10-17 15:47:35
【问题描述】:

我们如何在 Spring Security 配置中访问 webapp 的 WEB-INF 文件夹之外的 jdbc 属性?我的项目层次结构如下:

tomcat
  webapps
    appName
       Configuration
         jdbc.properties
         other configuration files too are here
      WebPages
         all the jsps/htmls here
      WEB-INF
         web.xml
         spring-security.xml
      classes/
      lib/
      tlds/ 

在 spring-security.xml 中,我试图引用 jdbc.properties 并且每次我得到文件未找到异常,

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="file:${catalina.home}/webapps/appName/configuration/jdbc.properties"/>

        <property name="location" value="file:${catalina.base}/webapps/appName/configuration/jdbc.properties"/>

<property name="location" value="/configuration/jdbc.properties"/>

<property name="location" value="file:/configuration/jdbc.properties"/>

<property name="location" value="classpath:/configuration/jdbc.properties"/>

<property name="location" value="classpath:/configuration/jdbc.properties"/>

</bean> 

{catalina.home} 和 {catalina.base} 工作,但仅在服务器重新启动或应用程序重新部署发生之前。 SO或互联网上的几乎所有答案都指向jdbc.properties文件放置在类路径中(即类文件夹内)的解决方案,但是由于内部原因,我不能在我的项目中这样做。

【问题讨论】:

  • 当然是把它们放在 CLASSPATH 中。它们属于 WEB-INF/classes。

标签: java tomcat configuration spring-security


【解决方案1】:

如果您将属性文件移动到 src/main/resources,假设您的项目由 maven 管理,那么您可以通过以下方式检索它

Properties prop = new Properties();

try {
    // load a properties file
    prop.load(YourClass.class.getResourceAsStream("/jdbc.properties")); // note the leading /

    System.out.println(prop.getProperty("password"));

} catch (IOException ex) {
    ex.printStackTrace();
}

YourClass 是这段代码所在的任何类。

Maven 将您编译的类的类文件和所有资源放在 WEB-INF/classes 中的 src/main/resources 中,只有您的应用程序可以访问它们。

如果您将文件放在 src/main/resources/someFolder 中,则需要从

访问它

prop.load(YourClass.class.getResourceAsStream("/someFolder/jdbcProperties")); 您提供给上述方法的路径是相对于您所在类的包的,除非您指定前导正斜杠,在这种情况下,它将相对于类路径的根目录,即类文件夹。

【讨论】:

  • 属性文件不在 src 中(它们与它平行),我没有使用 Maven。请查看相关项目结构。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2015-06-29
  • 2012-11-27
  • 2013-04-24
相关资源
最近更新 更多