Spring console application configured using annotations

后端 未结 7 1868
谎友^
谎友^ 2021-01-30 13:33

I want to create spring console application (running from command line with maven for example: mvn exec:java -Dexec.mainClass=\"package.MainClass\").

Is this application

7条回答
  •  一向
    一向 (楼主)
    2021-01-30 14:03

    This was my solution to run an exit. I use it in a module which works as common ground to all other specific ones: a website and an API one. When I specify the right arguments on the right module it will run the right task.

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.annotation.ComponentScan;
    
    @ComponentScan
    @EnableAutoConfiguration
    public class CLIApp {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext ctx =
                    new SpringApplicationBuilder(CLIApp.class)
                            .web(false)
                            .properties("spring.jmx.enabled=false")
                            .run(args);
    
            final int exitCode = SpringApplication.exit(ctx);
    
            System.out.println("************************************");
            System.out.println("* Console App sucessfully executed *");
            System.out.println("************************************");
    
            System.exit(exitCode);
        }
    }
    

    As you see, I also disabled the unused web environment and JMX. I will focus on scanning the classpath from the package of the class and use the autoconfiguration skills of Spring Boot. After the application finishes doing what it needs it closes like a console app.

提交回复
热议问题