java - How does the classloader find resources? -


i reviewing small github example project (shagie/testingwithhsqldb) , have stumbled across convention new me , hoping me understand looking at.


the project organized under main src directory such...

src/main/resources/connection_config.properties src/main/java/com/shagie/dbtest/db/dbconnection.java src/main/java/com/shagie/dbtest/db/dataaccess.java  src/test/resources/connection_config.properties src/test/java/com/shagie/dbtest/db/dataaccesstest.java 

the code in dbconnection.java called both dataaccess.java under 'main' directory dataaccesstest.java in 'test' directory.

in file dbconnection.java there following statement imports connection_config.properties file:

properties prop = new properties(); inputstream in = getclass().getresourceasstream("/connection_config.properties"); prop.load(in); in.close(); 

my questions...

  • how properties file being found in "resources" directory if call structured getresourceasstream("/connection_config.properties")? doesn't path mean should @ root directory (main or test) properties file?

  • since dbconnection.java doesn't change it's root 'main' directory, how properties file comes 'test' directory when executing dataaccesstest.java

  • i assume pattern related dependency injection , unit testing. there name specific pattern? place learn more it?

edit: adjusting question focus on classloader's getresource functionality instead of dependency injection

this has nothing dependency injection how classloaders resolve resource paths.

1) might bit confusing coming linux background indeed getresourceasstream(resource) has different rules. per doc:

if name begins '/' ('\u002f'), absolute name of resource portion of name following '/'.

so leading slash here tells class loader how absolute name (whether name passed should prepended package name or not), not should looking "at root" (in test/main folders). root , how resolution works depends on class loader using. default (in case) resources searched in resources folder. can write own classloader , change behavior.

2) again, when calling getresources() or getresourceasstream() class delegates classloader loaded class. if running unit tests (junit or similar) classloader know it's supposed resources in test folder not main.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -