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

标签 java spring-boot

我正在使用带有启动器的 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/

相关文章:

spring-boot - 在 Spring 启动:Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration)

css - Spring Boot - 不能包含静态资源

JAVAX JSR 356 Websocket 与 Spring Boot

java - 如何以编程方式将照片上传到图像托管服务器?

java - 我正在使用VideoView在我的应用程序中显示视频,但我不明白如何使pause()和resume()函数正常工作

java - 使用 Spring Boot 和 Thymeleaf 发送 HTML 电子邮件

java - 如何在 Java Spring 中的不同请求中使用 SET 的同一实例

java - 在 Windows 上外部化 Spring Boot application.properties 不工作

java - Hibernate映射保存问题

java - 如何替换字符串