Spring-从文件加载属性

时间:2019-05-23 13:43:36

标签: java spring spring-boot kotlin properties-file

假设我在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@

好吧,当我将鼠标悬停在IntelliJ上时,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类,以便从BASE_URL正确加载pom.xml属性(最好使BLOCK_THRESHOLD为{{1} } -injectable,但这不是优先事项)?

0 个答案:

没有答案
相关问题