如何在Spring中运行后置配置代码

huangapple go评论80阅读模式
英文:

How to run post configuration code in spring

问题

在我的测试中,我需要一些静态配置(rest客户端)。这段代码应该在所有配置文件加载完成后但在任何测试之前运行。它不会产生任何bean。

@TestConfiguration
class Config {

    // 如何注释这个方法?@PostConstruct 不起作用。这不是一个 @Bean 因为它是 void
    fun postConfiguration(env: Environment) {
        SomeClass.staticField = env.getProperty("xyz")
    }

}

如何使这个方法被执行?

英文:

In my tests i need to some static configuration (rest client). This code should run after all the config files are loaded but before any test. it doesn't produce any bean.

@TestConfiguration
class Config {
  
        // how to annotate this method? @PostConstruct won't work. it's not a @Bean as it's void
        fun postConfiguration(env: Environment) {
           SomeClass.staticField = env.getProperty("xyz")
        }

    }

How to make this method executed?

答案1

得分: 2

@Autowired 注解会解决问题,你可以像这样做:

@TestConfiguration
class Config {

    @Autowired
    fun postConfiguration(env: Environment) {
        SomeClass.staticField = env.getProperty("xyz")
    }

}
英文:

@Autowired annotation will do the trick you can do that like this:

@TestConfiguration
class Config {

    @Autowired
    fun postConfiguration(env: Environment) {
        SomeClass.staticField = env.getProperty("xyz")
    }

}

huangapple
  • 本文由 发表于 2020年10月21日 21:01:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64464141.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定