当前位置: 首页 > 科技观察

在SpringBoot中从类路径加载文件

时间:2023-03-15 10:11:33 科技观察

下面您将找到在WAR和JAR中加载文件的解决方案。资源加载器使用Java,你可以使用当前线程的classLoader并尝试加载文件,但是SpringFramework为你提供了更优雅的解决方案,比如ResourceLoader。您只需要自动装配ResourceLoader并调用getResource(?somePath“)方法。在SpringBoot(WAR)中从资源目录/类路径加载文件的示例在以下示例中,我们从类路径加载名为GeoLite2-Country.mmdb的文件作为资源,然后将其作为File对象检索。@Service("geolocationservice")publicclassGeoLocationServiceImplimplementsGeoLocationService{privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(GeoLocationServiceImpl.class);privatestaticDatabaseReaderreader=null;privateResourceLoaderresourceLoader;@AutowiredpublicGeoLocationServiceImpl(ResourceLoaderresourceLoader){this.resourceLoader=resourceLoader.void{logistConstruct()}"GeoLocationServiceImpl:TryingtoloadGeoLite2-Countrydatabase...");Resourceresource=resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");FiledbAsFile=resource.getFile();//Initializethereaderreader=newDatabaseReader.Builder(dbAsFile).fileMode(Reader.FileMode.MEMORY).build();LOGGER.info("GeoLocationServiceImpl:Databasewasloadedsuccessfully.");}catch(IOException|NullPointerExceptione){LOGGER.error("Databasereadercoundnotbeinitialized.",e);}}@PreDestroypublicvoidpreDestroy(){如果(读者!=null){尝试{reader.close();}catch(IOExceptione){LOGGER.error("Failedtoclosethereader.");}}}}在SpringBoot(JAR)中从资源目录/类路径加载文件的示例如果要从SpringBoot加载文件文件中的JAR类路径,您必须使用resource.getInputStream()方法将其检索为InputStream如果您尝试使用resource.getFile()方法,您将收到错误,因为Spring试图访问文件系统路径,但不能在JAR中找到路径。@Service("geolocationservice")publicclassGeoLocationServiceImplimplementsGeoLocationService{privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(GeoLocationServiceImpl.class);privatestaticDatabaseReaderreader=null;privateResourceLoaderresourceLoader;@InjectpublicGeoLocationServiceImpl(ResourceLoaderresourceLoader){this.resourceLoader=resourceLoader.{injectpublicGeoLocationServiceImpl(ResourceLoaderresourceLoader){this.resourceLoader=resourceLoader()}"GeoLocationServiceImpl:TryingtoloadGeoLite2-Countrydatabase...");Resourceresource=resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");InputStreamdbAsStream=resource.getInputStream();//<--thisisthedifference//Initializethereaderreader=newDatabaseReader.Builder(dbAsStream).fileMode(Reader.FileMode.MEMORY).build();LOGGER.info("GeoLocationServiceImpl:Databasewasloadedsuccessfully.");}catch(IOException|NullPointerExceptione){LOGGER.error("Databasereadercoundnotbeinitialized.",e);}}@PreDestroypublicvoidpreDestroy(){if(reader!=null){try{reader.close();}catch(IOExceptione){LOGGER.error("Failedtoclosethereader.");}}}}