java - Spring——从文件中加载属性
问题描述
假设我的pom.xml
文件中有一个属性
<webapp.base_url>http://localhost:8080</webapp.base_url>
而且我还有一个webapp.properties
文件包含
base_url=${webapp.base_url}
login.block_threshold=100
我现在想在 Spring Boot 中读取这些属性:
PropertySource("classpath:/com/blahblah/myapp/webapp.properties")
@Configuration
class Configuration @Inject constructor(
env: Environment
){
init {
Companion.env = env
}
companion object {
lateinit var env:Environment
private val LOG = LoggerFactory.getLogger(Configuration::class.java)
val BASE_URL: URL by lazy { URL(env.getProperty("base_url")) }
@Value("login.block_threshold")
var BLOCK_THRESHOLD: Int? = null
}
@PostConstruct
fun logConfig() {
LOG.info("Loaded webapp configuration:")
LOG.info("BASE_URL : {}", BASE_URL)
LOG.info("BLOCK_THRESHOLD : {}", BLOCK_THRESHOLD)
}
}
登录时BASE_URL
,我得到一个
java.lang.IllegalArgumentException: Could not resolve placeholder 'webapp.base_url' in value "${webapp.base_url}"
好吧,Spring 正在尝试查找${webapp.base_url}
,这意味着它至少正在访问webapp.properties
文件。也许我需要@ ... @
像使用application.properties
?
base_url=@webapp.base_url@
好吧,当我 ctrl-hover 时,IntelliJ 现在可以解决它,这是一个好兆头,对吗?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configuration': Invocation of init method failed;
nested exception is java.net.MalformedURLException: no protocol: @webapp.base_url@
不,显然不是。
而对于BLOCK_THRESHOLD
,我得到
BLOCK_THRESHOLD : null
看到BASE_URL
至少如何解决.properties
文件中的内容,这有点令人惊讶。所以也许我太早了......
val INITIAL_BLOCK_THRESHOLD: Int by lazy {env.getProperty("login.block_threshold")!!.toInt()}
是的,那个工作...
有没有办法重写我的Configuration
类,以便从(最好 是-injectable,但这不是优先事项)中BASE_URL
正确加载属性?pom.xml
BLOCK_THRESHOLD
@Value
解决方案
推荐阅读
- isabelle - 为什么我们需要证明这两个命题才能在 Isabelle 中应用析取消除?
- python - 使用 python 套接字流式传输视频并发送响应
- audio - IBM Watson Speech-to-Text“无法转码数据流音频/webm -> 音频/x-float-array”媒体 MIME 类型
- microsoft-graph-api - "表达式 \"fields(select\" 无效。"
- json - 如何从柏树测试中获取数据到 JSON 文件中?
- c# - 使用 .NET 反序列化 JSON
- javascript - 如何根据 react-native 中的条件导出对象?
- android - Android Studio 4.1 Canary:Firebase Crashlytics 破坏 android 项目编译
- javascript - 服务发出更改时组件模板变量不更新(角度)
- apt - mv:无法统计“pencil.desktop”:没有这样的文件或目录