首页 > 解决方案 > 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.xmlBLOCK_THRESHOLD@Value

标签: javaspringspring-bootkotlinproperties-file

解决方案


推荐阅读