1717package org .springframework .boot .jarmode .layertools ;
1818
1919import java .io .File ;
20+ import java .io .IOException ;
21+ import java .net .JarURLConnection ;
22+ import java .net .URISyntaxException ;
23+ import java .net .URL ;
24+ import java .net .URLConnection ;
2025import java .nio .file .Paths ;
26+ import java .security .CodeSource ;
27+ import java .security .ProtectionDomain ;
28+ import java .util .jar .JarFile ;
2129
22- import org .springframework .boot .system .ApplicationHome ;
2330import org .springframework .util .Assert ;
2431
2532/**
@@ -39,7 +46,7 @@ class Context {
3946 * Create a new {@link Context} instance.
4047 */
4148 Context () {
42- this (new ApplicationHome (). getSource (), Paths .get ("." ).toAbsolutePath ().normalize ().toFile ());
49+ this (getSourceJarFile (), Paths .get ("." ).toAbsolutePath ().normalize ().toFile ());
4350 }
4451
4552 /**
@@ -55,6 +62,39 @@ class Context {
5562 this .relativeDir = deduceRelativeDir (jarFile .getParentFile (), this .workingDir );
5663 }
5764
65+ private static File getSourceJarFile () {
66+ try {
67+ ProtectionDomain domain = Context .class .getProtectionDomain ();
68+ CodeSource codeSource = (domain != null ) ? domain .getCodeSource () : null ;
69+ URL location = (codeSource != null ) ? codeSource .getLocation () : null ;
70+ File source = (location != null ) ? findSource (location ) : null ;
71+ if (source != null && source .exists ()) {
72+ return source .getAbsoluteFile ();
73+ }
74+ return null ;
75+ }
76+ catch (Exception ex ) {
77+ return null ;
78+ }
79+ }
80+
81+ private static File findSource (URL location ) throws IOException , URISyntaxException {
82+ URLConnection connection = location .openConnection ();
83+ if (connection instanceof JarURLConnection ) {
84+ return getRootJarFile (((JarURLConnection ) connection ).getJarFile ());
85+ }
86+ return new File (location .toURI ());
87+ }
88+
89+ private static File getRootJarFile (JarFile jarFile ) {
90+ String name = jarFile .getName ();
91+ int separator = name .indexOf ("!/" );
92+ if (separator > 0 ) {
93+ name = name .substring (0 , separator );
94+ }
95+ return new File (name );
96+ }
97+
5898 private String deduceRelativeDir (File sourceFolder , File workingDir ) {
5999 String sourcePath = sourceFolder .getAbsolutePath ();
60100 String workingPath = workingDir .getAbsolutePath ();
0 commit comments