java) Value annotation and classpath

@Value(classpath)

When using @Value("classpath:...")
  • External Resources: If resources can be found on the external file system, @Value loads them as file paths.
  • Internal JAR Resources: Resources embedded within a JAR cannot be directly accessed as file paths and must be read through getInputStream(). Spring automatically provides these resources via a Resource object in this case. Resources can be read using an InputStream.

When deploying as a WAR

  • Tomcat adds WEB-INF/classes/ (a path on the actual file system) of the directory where the WAR is extracted to the classpath.
  • Resources can be accessed directly.
1@Value("classpath:menu.xml")  
2private Resource menuFile;
3
4...
5
6menuFile.getFile()

When deploying as a JAR

  • getFile() is expected to return a File object, but files inside a JAR are compressed and cannot be directly converted to a File.
  • The resource is read directly from within the compressed JAR using getInputStream().
1@Value("classpath:menu.xml")  
2private Resource menuFile;
3
4...
5
6try (InputStream inputStream = menuFile.getInputStream())...

Post
Category
Series