gpt4 book ai didi

java - Spring 启动器 : Missing Bean instead of missing value

转载 作者:行者123 更新时间:2023-11-30 07:14:20 28 4
gpt4 key购买 nike

我正在使用带有启动器的 Spring Boot。当我错误配置启动器(缺少或定义了错误的值)时,它会打印“缺少 bean”错误消息,而不是“缺少值”。很难找到这个错误。

我的开胃菜看起来像

@ConditionalOnProperty(name = "my.starter.value")
@Configuration
public class MyStarterConfiguration {

@Bean
public MyStarterExample myStarterExample(@Value("${my.starter.value}") String s) {
return new MyStarterExample(s);
}

spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.MyStarterConfiguration

如果键 my.starter.value 丢失,我希望看到一条错误消息,提示“my.stater.value 丢失”。不幸的是它只打印出bean丢失了。这也太不精确了吧如果主应用程序缺少值,则会打印这样的错误消息。

[...] org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.MyStarterExample [...]

您能帮助我配置为我的启动器打印更精确的错误消息吗?

<小时/>

如何重现:下载完整源代码https://drive.google.com/file/d/0BzbrQ3P_g0Z3U2dxbGE0enR1ZHM/view?usp=sharing

unzip my.problem.zip
cd my.starter/
mvn clean install
cd ../my.application/
mvn clean package
java -jar target/my.application-0.0.1-SNAPSHOT.jar

现在错误配置主应用程序的值src/main/resources/application.properties

my.starter.value=my.starter.value
my.app.value_=my.app.value

重新启动

mvn clean package
java -jar target/my.application-0.0.1-SNAPSHOT.jar

其中有一条错误消息

java.lang.IllegalArgumentException: Could not resolve placeholder 'my.app.value' in string value "${my.app.value}"

没关系。

现在错误配置了启动器的值src/main/resources/application.properties

my.starter.value_=my.starter.value
my.app.value=my.app.value

重新启动

mvn clean package
java -jar target/my.application-0.0.1-SNAPSHOT.jar

只有一条关于缺少 bean 的错误消息

[...] org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.MyStarterExample [...]

这很尴尬。我希望看到缺失值,例如应用程序值。

最佳答案

您明确使用@ConditionalOnProperty(name = "my.starter.value"),其中 basically means “仅当属性 my.starter.value 存在且不等于 false 时才应用此 @Configuration”。所以 Spring boot 正是这样做的 - 当没有 my.starter.value 属性(您重命名它)时,它不会应用该配置,并且不会创建 MyStarterExample bean ,这会在需要该 bean 的地方导致 NoSuchBeanDefinitionException

关于java - Spring 启动器 : Missing Bean instead of missing value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38694820/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com