java – Spring启动CommandLineRunner异常处理

我们使用Spring-boot作为命令行应用程序.我们使用javax.validation来验证命令行参数.

现在,如果我们有验证错误,我们如何打印友好的错误消息?我们不想显示堆栈跟踪.

我们在运行Spring-boot作为CommandLineRunner时是否可以使用ExceptionHandler机制?

谢谢
阿伦

资源

    @SpringBootApplication
    public class Deploy implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(Deploy.class);

    @Autowired
    private DeployConfig config;

    @Autowired
    private DeployService deployService;

    /**
     * mvn clean package spring-boot:repackage
     * java -jar target/spring-boot-example-1.0.0-SNAPSHOT.jar --spring.profiles.active=qa --version=1.0
     *
     * @param strings arguments
     * @throws Exception
     */

    @Override
    public void run(String... strings) throws Exception {
        try {
            deployService.deploy(config);
        } catch (Exception ve) {
            LOGGER.error("Error : {}",ve.getMessage());
        }

        LOGGER.info("Created stack={}",config.getVersion());
    }

    public static void main(String... args) {
        LOGGER.info("Starting to run...");
        SpringApplication.run(Deploy.class,args);
        LOGGER.info("Completed the run...");
    }
}

组态

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class DeployConfig {

    @NotNull
    private String hello;

    @NotNull
    private String version;

    private String envKey;

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getEnvKey() {
        return envKey;
    }

    public void setEnvKey(String envKey) {
        this.envKey = envKey;
    }

    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

清洁运行

mvn clean package spring-boot:repackage
java -jar target/spring-boot-example-1.0.0-SNAPSHOT.jar --spring.profiles.active=preprod,qa --version=1.0

验证检查

java -jar target/spring-boot-example-1.0.0-SNAPSHOT.jar --spring.profiles.active=preprod,qa

验证错误

2014-12-25 20:51:13,325 ERROR [main] [o.s.b.SpringApplication.run()] - Application startup Failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'deploy': Injection of autowired dependencies Failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.DeployConfig com.example.Deploy.config; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'deployConfig': Could not bind properties; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'target' on field 'version': rejected value [null]; codes [NotNull.target.version,NotNull.version,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.version,version]; arguments []; default message [version]]; default message [may not be null]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcesspropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.3.RELEASE.jar!/:4.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapablebeanfactory.populateBean(AbstractAutowireCapablebeanfactory.java:1202) ~[spring-beans-4.1.3.RELEASE.jar!/:4.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapablebeanfactory.doCreateBean(AbstractAutowireCapablebeanfactory.java:537) ~[spring-beans-4.1.3.RELEASE.jar!/:4.1.3.RELEASE]

完整来源

来源可以在GitHub找到

最佳答案
我遇到(几乎)同样的问题,并且(令我惊讶的是)似乎从Spring Boot命令行程序向用户显示错误的最简洁方法是从CommandlineRunner实际上是System.exit(1).在记录您想要的任何错误消息后运行().无论如何,Spring上下文将干净地关闭,但它不会触发上下文启动失败事件,因此您不会获得所有其他令人分心的日志输出.

您可能必须调整调用验证的方式,以便您可以在run()中自己捕获验证错误并将它们转换为日志System.exit().

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...