@PostConstruct publicvoidinit() { try { LOGGER.info("GeoLocationServiceImpl: Trying to load GeoLite2-Country database..."); Resourceresource= resourceLoader.getResource("classpath:GeoLite2-Country.mmdb"); FiledbAsFile= resource.getFile(); // Initialize the reader reader = newDatabaseReader .Builder(dbAsFile) .fileMode(Reader.FileMode.MEMORY) .build(); LOGGER.info("GeoLocationServiceImpl: Database was loaded successfully."); } catch (IOException | NullPointerException e) { LOGGER.error("Database reader cound not be initialized. ", e); } } @PreDestroy publicvoidpreDestroy() { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("Failed to close the reader."); } } } }
从 SpringBoot FatJar 中加载资源
如果我们想从 Spring Boot JAR 中的类路径加载文件,则必须使用 resource.getInputStream() 方法将其作为 InputStream 检索。 如果尝试使用resource.getFile(),则会收到错误消息,因为 Spring 尝试访问文件系统路径,但它无法访问 JAR 中的路径。