如何配置 Spring 以从 jar 外部加载 application.properties?
How to configure Spring to load application.properties from outside of jar?
我想要这样的目录结构:
/Directory
- Application.jar
- application.properties
这样我就可以更改属性而不必重新打包和重新部署(而只是重新启动 jar)。如何使用 spring 注释或配置 类 完成此操作?
我不是要让外部资源在我的 Web 应用程序中可用,我还想更改 spring 加载 application.properties 文件的位置。
您可能想探索 PropertyPlaceholderExplorer class in Spring. This class provides the facility to access the properties file external to your jar/war bundle. There is a short nice tutorial on this as well here。
如果您开始使用 Spring 引导(在某个阶段您肯定会)。你变得强大 configuration externalization features。
使用 Spring 引导,您的 applications.properties 会自动加载到 Spring 引导上下文中,您可以使用 ${...}
占位符。
您可以使用更现代的功能 @ConfigurationProperties 将您的配置映射到 POJO。此 POJO 甚至可以通过 Java EE 验证注释(例如 @NotNull)
进行验证
你提到了 jar,那么你正在使用 Spring 引导?
如果是这样,同一目录中的外部 application.properties(结构与您描述的一样)将覆盖打包在 jar 文件中的 application.properties。
然后,如果您的 application.properties 中有类似 key=value
的内容,您可以使用 @Value("${key}") String key
.
将其注入代码中
试一试,它会起作用:)
我想要这样的目录结构:
/Directory
- Application.jar
- application.properties
这样我就可以更改属性而不必重新打包和重新部署(而只是重新启动 jar)。如何使用 spring 注释或配置 类 完成此操作?
我不是要让外部资源在我的 Web 应用程序中可用,我还想更改 spring 加载 application.properties 文件的位置。
您可能想探索 PropertyPlaceholderExplorer class in Spring. This class provides the facility to access the properties file external to your jar/war bundle. There is a short nice tutorial on this as well here。
如果您开始使用 Spring 引导(在某个阶段您肯定会)。你变得强大 configuration externalization features。
使用 Spring 引导,您的 applications.properties 会自动加载到 Spring 引导上下文中,您可以使用 ${...}
占位符。
您可以使用更现代的功能 @ConfigurationProperties 将您的配置映射到 POJO。此 POJO 甚至可以通过 Java EE 验证注释(例如 @NotNull)
进行验证你提到了 jar,那么你正在使用 Spring 引导?
如果是这样,同一目录中的外部 application.properties(结构与您描述的一样)将覆盖打包在 jar 文件中的 application.properties。
然后,如果您的 application.properties 中有类似 key=value
的内容,您可以使用 @Value("${key}") String key
.
试一试,它会起作用:)