16
16
17
17
package org .springframework .boot .autoconfigure ;
18
18
19
+ import java .util .concurrent .CountDownLatch ;
20
+ import java .util .concurrent .atomic .AtomicBoolean ;
21
+
19
22
import javax .validation .Validation ;
20
23
21
24
import org .apache .catalina .mbeans .MBeanFactory ;
22
25
23
26
import org .springframework .boot .context .event .ApplicationEnvironmentPreparedEvent ;
27
+ import org .springframework .boot .context .event .ApplicationFailedEvent ;
28
+ import org .springframework .boot .context .event .ApplicationReadyEvent ;
29
+ import org .springframework .boot .context .event .SpringApplicationEvent ;
24
30
import org .springframework .boot .context .logging .LoggingApplicationListener ;
25
31
import org .springframework .context .ApplicationListener ;
26
32
import org .springframework .core .annotation .Order ;
38
44
*/
39
45
@ Order (LoggingApplicationListener .DEFAULT_ORDER + 1 )
40
46
public class BackgroundPreinitializer
41
- implements ApplicationListener <ApplicationEnvironmentPreparedEvent > {
47
+ implements ApplicationListener <SpringApplicationEvent > {
48
+
49
+ private static final AtomicBoolean preinitalizationStarted = new AtomicBoolean (false );
50
+
51
+ private static final CountDownLatch preinitializationComplete = new CountDownLatch (1 );
42
52
43
53
@ Override
44
- public void onApplicationEvent (ApplicationEnvironmentPreparedEvent event ) {
54
+ public void onApplicationEvent (SpringApplicationEvent event ) {
55
+ if (event instanceof ApplicationEnvironmentPreparedEvent ) {
56
+ if (preinitalizationStarted .compareAndSet (false , true )) {
57
+ performPreinitialization ();
58
+ }
59
+ }
60
+ if (event instanceof ApplicationReadyEvent
61
+ || event instanceof ApplicationFailedEvent ) {
62
+ try {
63
+ preinitializationComplete .await ();
64
+ }
65
+ catch (InterruptedException ex ) {
66
+ Thread .currentThread ().interrupt ();
67
+ }
68
+ }
69
+ }
70
+
71
+ private void performPreinitialization () {
45
72
try {
46
73
Thread thread = new Thread (new Runnable () {
47
74
@@ -52,6 +79,7 @@ public void run() {
52
79
runSafely (new ValidationInitializer ());
53
80
runSafely (new JacksonInitializer ());
54
81
runSafely (new ConversionServiceInitializer ());
82
+ preinitializationComplete .countDown ();
55
83
}
56
84
57
85
public void runSafely (Runnable runnable ) {
@@ -70,6 +98,7 @@ public void runSafely(Runnable runnable) {
70
98
// This will fail on GAE where creating threads is prohibited. We can safely
71
99
// continue but startup will be slightly slower as the initialization will now
72
100
// happen on the main thread.
101
+ preinitializationComplete .countDown ();
73
102
}
74
103
}
75
104
0 commit comments