【发布时间】:2021-07-25 21:14:55
【问题描述】:
最近我在 Spring 中连接 bean 时出错,导致我无法复制的行为。部署应用程序时,使用了在 @Configuration 中定义的另一个 String 类型的 bean 的值,而不是将源自 @Value 的属性注入到 Stuff(参见下面的完整演示代码)中。
我觉得令人费解的是,在本地运行时(包括单元测试),一切都按预期工作,输出是 foo 而不是 kaboom,而且这种“bean 交换”在部署时发生,而不是“否”合格 bean' 错误。
注释掉的行显示了我认为使配置类似于the manual 中的配置的修复。
我的设置有什么问题?什么会使所示代码(即没有修复)使用 kaboom String 而不是 foo 属性?
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
open class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
open class Config {
// ...beans of types other than String in original code...
@Bean
open fun beanBomb(): String {
return "kaboom"
}
@Bean
// fix:
// @Value("\${stuff}")
open fun beanStuff(stuff: String): Stuff {
return Stuff(stuff)
}
}
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
@Component
class Stuff(@Value("\${stuff}") val stuff: String)
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import javax.annotation.PostConstruct
@Component
class Init {
@Autowired
private lateinit var stuff: Stuff
@PostConstruct
fun init() {
println("stuff: " + stuff.stuff)
}
}
// application.properties
stuff=foo
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@TestPropertySource(properties = {"stuff=testFoo"})
class DemoApplicationTests {
@SpyBean
private Stuff stuff;
@Test
void test() {
assertEquals("testFoo", stuff.getStuff());
}
}
另外,应用修复后,Stuff 中的 @Value 注释是否必要?如果我取消注释修复,请从 Stuff 中删除 @Value 并将以下注释添加到测试通过的测试类:
@ContextConfiguration(classes = {Config.class})
但是当我运行应用程序时,它会打印kaboom...
【问题讨论】:
-
在
Stuff类上放置@Component注解并同时在java配置中定义它有什么意义(带有@Bean注解的方法)?
标签: spring spring-boot kotlin properties-file spring-annotations