如何使用@autowired在springboot中做一个简单的“失败”主程序?

问题描述 投票:2回答:2

我想使用Spring Boot做一个简单的主程序,并自动连接一些字段。

如果进程中引发某些异常,我希望应用程序失败(错误代码!= 0)。>

示例:

@SpringBootApplication
public class SqlInserterMain
{
    @Autowired
    private static JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(SqlInserterMain.class, args);

        insertData();

        context.close();
    }

    private static void insertData()
    {
        // Do something with jdbcTemplate.
        // If jdbcTemplate fails on exception, the app should fail and return some error code.
        System.out.println("YOYO" + jdbcTemplate);
    }
}

但是jdbcTemplate为空。

如果添加@componentApplicationRunner,则@autowire可以使用,但我不会让主电源失效。

任何想法如何对一些自动连接的字段进行快速而简单的处理,这些字段在发生异常时会失败?谢谢。

我想使用Spring Boot做一个简单的主程序,并自动连接一些字段。如果进程中引发了异常,我希望该应用程序失败(错误代码!= 0)。例如:@SpringBootApplication ...

java spring-boot main
2个回答
1
投票

[我不认为SqlInserterMain被认为是由Spring管理的bean(嗯,它没有被Spring实例化,对吗?)。只需创建一个额外的bean(如yAzou所述)或从Spring上下文中手动提取JdbcTemplate。


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.