创建Spring Boot Web应用程序时,有时有时需要从类路径中加载文件;war和jar的加载文件格式是不一样的
在下面,您将找到在WAR和JAR中加载文件的解决方案。
资源加载器
使用Java,您可以使用当前线程的classLoader并尝试加载文件,但是Spring Framework为您提供了更为优雅的解决方案,例如ResourceLoader。
您只需要自动连接ResourceLoader,然后调用getResource(„somePath“)方法即可。
在Spring Boot(WAR)中从资源目录/类路径加载文件的示例
在以下示例中,我们从类路径中加载名为GeoLite2-Country.mmdb的文件作为资源,然后将其作为File对象检索。
- @Service("geolocationservice")
- publicclassGeoLocationServiceImplimplementsGeoLocationService{
- privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(GeoLocationServiceImpl.class);
- privatestaticDatabaseReaderreader=null;
- privateResourceLoaderresourceLoader;
- @Autowired
- publicGeoLocationServiceImpl(ResourceLoaderresourceLoader){
- this.resourceLoader=resourceLoader;
- }@PostConstruct
- publicvoidinit(){
- try{
- LOGGER.info("GeoLocationServiceImpl:TryingtoloadGeoLite2-Countrydatabase...");
- Resourceresource=resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
- FiledbAsFile=resource.getFile();//Initializethereader
- reader=newDatabaseReader
- .Builder(dbAsFile)
- .fileMode(Reader.FileMode.MEMORY)
- .build();
- LOGGER.info("GeoLocationServiceImpl:Databasewasloadedsuccessfully.");
- }catch(IOException|NullPointerExceptione){
- LOGGER.error("Databasereadercoundnotbeinitialized.",e);
- }
- }
- @PreDestroy
- publicvoidpreDestroy(){
- if(reader!=null){
- try{
- reader.close();
- }catch(IOExceptione){
- LOGGER.error("Failedtoclosethereader.");
- }
- }
- }
- }
在Spring Boot(JAR)中从资源目录/类路径加载文件的示例
如果您想从Spring Boot JAR中的 classpath加载文件,则必须使用该resource.getInputStream()方法将其作为InputStream检索。如果尝试使用resource.getFile()该方法,则会收到错误消息,因为Spring尝试访问文件系统路径,但无法访问JAR中的路径。
- @Service("geolocationservice")
- publicclassGeoLocationServiceImplimplementsGeoLocationService{
- privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(GeoLocationServiceImpl.class);
- privatestaticDatabaseReaderreader=null;
- privateResourceLoaderresourceLoader;
- @Inject
- publicGeoLocationServiceImpl(ResourceLoaderresourceLoader){
- this.resourceLoader=resourceLoader;
- }@PostConstruct
- publicvoidinit(){
- try{
- LOGGER.info("GeoLocationServiceImpl:TryingtoloadGeoLite2-Countrydatabase...");
- Resourceresource=resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
- InputStreamdbAsStream=resource.getInputStream();//<--thisisthedifference
- //Initializethereader
- reader=newDatabaseReader
- .Builder(dbAsStream)
- .fileMode(Reader.FileMode.MEMORY)
- .build();
- LOGGER.info("GeoLocationServiceImpl:Databasewasloadedsuccessfully.");
- }catch(IOException|NullPointerExceptione){
- LOGGER.error("Databasereadercoundnotbeinitialized.",e);
- }
- }
- @PreDestroy
- publicvoidpreDestroy(){
- if(reader!=null){
- try{
- reader.close();
- }catch(IOExceptione){
- LOGGER.error("Failedtoclosethereader.");
- }
- }
- }
- }
©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经