首页 文章

Spring Boot Devtools:检测自动重启并应用配置

提问于
浏览
0

我想设置仅在Spring Boot开发人员工具提供的自动重启期间应用的属性 . 有没有办法实现这个目标?

换句话说,我的代码的某些部分(可能是配置bean或侦听器)是否有办法检测重启是否正在进行?

在我的特定用例中,我想在常规Spring Boot应用程序启动期间运行一些SQL脚本,但是在Devtools触发重启后不会运行(因此我的数据库状态在重启期间不会更改) .

1 回答

  • 0

    这是一个想法:

    它's confusing to explain, but you'将看到下面的代码 . 当Spring-Boot在其依赖项中以 devtools 开始时,它首先启动,然后立即重新启动第一次通过 devtools . 您可以动态添加命令行参数来跟踪重新启动并更改 devtools 重新启动时使用的Spring配置文件:

    @SpringBootApplication
    public class App {
        public static void main(String[] args)
                throws ParseException, IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    
            String profile = "";
    
            //(1) Very first time - Spring Boot doesn't really load, it only kick start devtool then restarts.
            if (args.length == 0) {
                args = new String[] { "spring-boot-loaded" };
                profile = "no-devtools-yet";
            } 
    
            //(2) The first time the application loads with devtools
            else if (args.length == 1 && args[0].equals("spring-boot-loaded")) {
                args = new String[] { "spring-boot-loaded", "devtools-loaded" };
                profile = "devtools";
                Field argsField = Restarter.class.getDeclaredField("args");
                argsField.setAccessible(true);
                argsField.set(Restarter.getInstance(), args);
            } 
    
            //(3) This is the first restart - You don't want to re-initialized the database here
            else {
                profile = "devtools-reloaded";
            }
    
            new SpringApplicationBuilder() //
                    .sources(App.class)//
                    .profiles(profile) //
                    .run(args);
        }
    }
    

    粗略的部分是 Restarter 保留原始参数(在本例中为"no-devtools-yet") . 因此,当 devtools 首次启动时,您需要替换 Restarter 的内部参数

相关问题