1 background

In the actual project development process, we will use data processing, data initialization and other non-Web projects, but we want to use springboot to bring us convenience

2 solutions

We’ll come up with different solutions to the actual problem

Scheme 2.1 a

Pom file

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>Copy the code

Through the appeal we can see that we have introduced the Web project

Application. The yaml file

Spring: Application: name: demo # Run non-Web main: web-application-type: None Server: port: 8080Copy the code

@postconstruct Complete the task

Public class DemoApplication {@postconstruct public void init(){system.out.println (" I am the initializing method "); } public static void main(String[] args) { SpringApplication application= new SpringApplication(DemoApplication.class); //application.addListeners(new ApplicationStartingEventistener()); application.run(args); //ScheduledExecutorService timer = Executors.newScheduledThreadPool(2); }}Copy the code

The results

The 2021-03-24 11:35:06. 51476-776 the INFO [main] com. Example. Demo. DemoApplication: Starting DemoApplication using Java 1.8.0_181 on DESKTOP-J55VRAQ with PID 51476 (C:\Users\baicells\eclipse-workspace\demo\target\classes started by baicells in C:\Users\baicells\ Eclipse-workspace \demo) 2021-03-24 11:35:06.782 INFO 51476 -- [main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: The default initialization method I am 11:35:09 2021-03-24. 226 INFO 51476 - [the main] com. Example. Demo. DemoApplication: Started DemoApplication in 4.286 seconds (JVM running for 6.326) Disconnected from the target VM, address: '127.0.0.1:49953', transport: 'socket' Process finished with exit code 0Copy the code

2.2 2

Pom file

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>Copy the code

Through the appeal we can see that we have introduced the Web project

Application. The yaml file

Spring: Application: name: demo # Run non-Web main: web-application-type: None Server: port: 8080Copy the code

SmartLifecycle completes tasks

@Component public class TestSmartLifecycle implements SmartLifecycle { private boolean isRunning = false; /** * 1. We mainly start tasks or other asynchronous services in this method, such as enabling MQ receive elimination. This method is called when the context is refreshed (after all objects have been instantiated and initialized) and the default life cycle handler checks the Boolean value returned by the isAutoStartup() method of each SmartLifecycle object. * If true, the method is called instead of waiting explicitly to call its own start() method. */ @Override public void start() { System.out.println("start"); IsRunning = true isRunning = true } /** * If there are multiple classes in the project that implement the interface SmartLifecycle, the start of those classes will be executed in descending order from the value returned by the getPhase method. <br/> * For example, 1 to 2 is executed first, and -1 to 0 is executed first. The stop methods are executed in the opposite order, with getPhase returning larger categories of stop methods called first and smaller ones called later. */ @override public int getPhase() {return 0; } /** * Determines whether to execute the start method based on the return value of the method. The start method is executed automatically if <br/> * returns true, but not if false. */ @override public Boolean isAutoStartup() {return true; } /** * 1. The start method is executed only if the method returns false. <br/> * 2. The stop(Runnable callback) or stop() methods will only be executed if the method returns true. */ @override public Boolean isRunning() {false return isRunning; } /** * a SmartLifecycle subclass method that will be called when isRunning returns true. */ @Override public void stop(Runnable callback) { System.out.println("stop(Runnable)"); // If you want isRunning to return true and need to stop, don't forget to call callback.run(). / / otherwise when you program exits, Spring's DefaultLifecycleProcessor will think that you complete the TestSmartLifecycle did not stop, the program will have been card won't end, waiting for a certain period of time (default timeout after 30 seconds) will automatically end. // PS: If you want to change the default timeout, you can do the following. Of course, the following code is a reference in the form of springMVC configuration file. // <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor"> // <! -- timeout value in milliseconds --> // <property name="timeoutPerShutdownPhase" value="10000"/> // </bean> callback.run(); isRunning = false; } /** * a method of a subclass of the Lifecycle interface that will only be executed by non-SmartLifecycle subclasses. <br/> * 1. This method will only work with classes that directly implement the interface Lifecycle, not with classes that implement the SmartLifecycle interface. <br/> * 2. The method stop() differs from the method stop(Runnable callback) only in that the latter is exclusive to the SmartLifecycle subclass. */ @Override public void stop() { System.out.println("stop"); isRunning = false; }Copy the code

The results

The 2021-03-24 11:36:30. 49516-257 the INFO [main] com. Example. Demo. DemoApplication: Starting DemoApplication using Java 1.8.0_181 on DESKTOP-J55VRAQ with PID 49516 (C:\Users\baicells\eclipse-workspace\demo\target\classes started by baicells in C:\Users\baicells\ Eclipse-workspace \demo) 2021-03-24 11:36:30.266 INFO 49516 -- [main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: Default initialization method I am start 11:36:32 2021-03-24. 49516-355 the INFO [main] com. Example. Demo. DemoApplication: Started DemoApplication in 3.883 seconds (JVM running for 5.505) stop(Runnable) Disconnected from the target VM, Address: '127.0.0.1:49993', transport: 'socket' Process finished with exit code 0Copy the code

conclusion

When implementing the SmartLifecycle interface, the start method is executed after the container is loaded and the stop method is executed before the container is destroyed

2.3 plan three

Pom file

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>  <scope>test</scope> </dependency> </dependencies>Copy the code

Through the appeal we can see that we didn’t introduce the Web project

Application. The yaml file

spring:
  application:
    name: demo
Copy the code

@postconstruct Complete the task

public class DemoApplicationCommandLineRunner implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(DemoApplicationCommandLineRunner.class,args); } @Override public void run(String... Args) throws Exception {system.out.println (" I am CommandLineRunner"); }}Copy the code

The results

The 2021-03-24 11:46:49. 51928-797 the INFO [the main] C.E.D.D emoApplicationCommandLineRunner: Starting DemoApplicationCommandLineRunner using Java 1.8.0 comes with _181 on the DESKTOP - J55VRAQ with PID 51928 (C:\Users\baicells\eclipse-workspace\demo\target\classes started by baicells in C:\Users\baicells\ Eclipse-workspace \demo) 2021-03-24 11:46:49.803 INFO 51928 -- [main] c.e.d.DemoApplicationCommandLineRunner : No active profile set, falling back to default profiles: Default initialization method I am start 11:46:51 2021-03-24. 51928-429 the INFO [main] C.E.D.D emoApplicationCommandLineRunner: Started DemoApplicationCommandLineRunner in 2.819 seconds (JVM running for 4.259) I am CommandLineRunner stop (Runnable) Process finished with exit code 0Copy the code

2.4 plan 4

Implement ApplicationListener listening

public class TestListener implements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationStartingEvent) { System.out.println("1111"); {} the if (event instanceof ApplicationEnvironmentPreparedEvent) System. The out. Println (" environment initialization!!!" ); } else if (Event Instanceof ApplicationPreparedEvent){system.out.println (" Initialization is complete!! ") ); } else if (event instanceof ContextRefreshedEvent) {system.out.println (" App refresh!!" ); } else if (Event Instanceof ApplicationReadyEvent) {system.out.println (" Project started!! ") ); } else if (Event instanceof ContextStartedEvent) {system.out.println (" Application started!! ") ); } else if (Event instanceof ContextStoppedEvent) {system.out.println (" Project stopped!! "); ); } else if (Event instanceof ContextClosedEvent) {system.out.println (" Application closed!!" ); }}}Copy the code

The container joins custom listeners

1: added in the startup class

SpringApplication application= new SpringApplication(DemoApplication.class);
application.addListeners(new TestListener());
Copy the code

2 or specified in the configuration file:

# configuration start listening context: the listener: classes: com. Example. Demo. TestListenerCopy the code