Task: In the same directory with the jar-file is the properties file that you want to read.

Here I was advised such a code

URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI(); String path = new File(uri).getParent(); 

Everything worked fine until I contacted the spring-boot.

In the case of a regular jar, uri is returned in the form file:/path/name-of-jar.jar and everything works. But when using spring-boot, the address is a different jar:file:/path/name-of-jar.jar!/BOOT-INF/classes!/ And the subsequent call

 new File(uri) 

falls with an error

java.lang.IllegalArgumentException: URI is not hierarchical

Is it somehow being treated? Here it is advised to simply trim the string to the desired type. But somehow I don’t really like the method

  • And this properties file can not be put in resources? - Komdosh pm
  • @Komdosh No There are settings for connecting to the database and they should be editable - Anton Shchyrov
  • what for? Maybe you need to use profiles in spring? - Komdosh
  • @Komdosh This is an independent library that knows nothing about spring - Anton Shchyrov
  • Try this at stackoverflow.com/questions/46657181/… - Komdosh 1:32 pm

2 answers 2

Such code turned out

 public static String getParentRealPath(URI uri) throws URISyntaxException { if (!"jar".equals(uri.getScheme())) return new File(uri).getParent(); do { uri = new URI(uri.getSchemeSpecificPart()); } while ("jar".equals(uri.getScheme())); File file = new File(uri); do { while (!file.getName().endsWith(".jar!")) file = file.getParentFile(); String path = file.toURI().toString(); uri = new URI(path.substring(0, path.length() - 1)); file = new File(uri); } while (!file.exists()); return file.getParent(); } URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI(); System.out.println(getParentRealPath(uri)); 

    The library may not know about the spring, but the spring knows something about it.

    In my opinion, you can create a class with the @Configuration annotation, add @PropertySource , in which you can correctly set the path to the external file. This class via @Value ("$ {some-key-from-property-file}") will be able to get values ​​into the fields of this class, in the same class create methods with @Bean annotation that will create objects of your library using values from the file.