-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSpringBootContextLoader.java
More file actions
56 lines (43 loc) · 2.51 KB
/
SpringBootContextLoader.java
File metadata and controls
56 lines (43 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package net.dempsy.util.spring;
import java.io.IOException;
import java.lang.reflect.Method;
import org.springframework.boot.SpringApplication;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import net.dempsy.util.QuietCloseable;
public class SpringBootContextLoader {
// public static ConfigurableApplicationContext load(final Class[] propertyContexts, )
public static ConfigurableApplicationContext load(final String[] propertyCtx, final Class<?> appCtx2, final String[] args) throws IOException {
return load(propertyCtx, null, appCtx2, args);
}
public static ConfigurableApplicationContext load(final String[] propertyCtx, final String[] parentCtx, final Class<?> springBootApp, final String[] args)
throws IOException {
final ClassPathXmlApplicationContext pCtx = SpringContextLoader.load(propertyCtx, parentCtx);
try(final ClassPathXmlApplicationContext propsCtx = new ClassPathXmlApplicationContext(propertyCtx);) {
final SpringApplication app = new SpringApplication(springBootApp);
app.addInitializers(appCtx -> {
final ApplicationContext curParent = appCtx.getParent();
if(curParent != null) throw new IllegalStateException(
"Cannot use the " + SpringBootContextLoader.class.getSimpleName() + " to augment a context that already has a parent. Sorry.");
appCtx.setParent(pCtx);
});
final var ret = app.run(args);
return wrapConfigurableApplicationContext(ret, () -> pCtx.close());
}
}
private static final ConfigurableApplicationContext wrapConfigurableApplicationContext(final ConfigurableApplicationContext ret,
final QuietCloseable additional) {
return (ConfigurableApplicationContext)Enhancer.create(ConfigurableApplicationContext.class,
(MethodInterceptor)(final Object obj, final Method method, final Object[] args, final MethodProxy proxy) -> {
final Object result = proxy.invoke(ret, args);
if("close".equals(method.getName()) && (args == null || args.length == 0)) {
additional.close();
}
return result;
});
}
}