如何从spring实例化的POJO类(不是servlet)中读取manifest.mf? [英] How to read manifest.mf from POJO class (not a servlet) instantiated by spring?

查看:138
本文介绍了如何从spring实例化的POJO类(不是servlet)中读取manifest.mf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为BuildNumberService的简单服务,该服务将在spring实例化.

I have a simple service called BuildNumberService which would be instantiated by spring.

我正在尝试为该类找到最干净的代码,以从打包到其的jar文件中找出MANIFEST.MF文件.

I'm trying to find the cleanest code for the class to find out the MANIFEST.MF file from the jar file it has been packaged into.

代码必须在servlet容器中运行.

The code has to run inside a servlet container.

@Service
public class BuildNumberService {

    private static final String IMPLEMENTATION_BUILD = "Implementation-Build";

    private String version = null;

    public BuildNumberService() {

      // find correct manifest.mf
      // ?????


      // then read IMPLEMENTATION_BUILD attributes and caches it.
       Attributes mainAttributes = mf.getMainAttributes();
       version = mainAttributes.getValue(IMPLEMENTATION_BUILD);
    }

    public String getVersion() {
        return this.version;
    }
}

你会怎么做?

实际上,我想做的是,按名称查找与实际类位于同一包中的资源.

Actually, what I'm trying to do, is, find a resource by name which sits in the same package as the actual class.

推荐答案

好吧,如果您知道jar位于文件系统上(例如不在战争中),并且您还知道安全管理器已授予您访问权限的权限,类的保护域,您可以这样操作:

Well if you know the jar is on the file system (e.g. not inside a war) and you also know that the security manager gives you the permission to access a class' protection domain, you can do it like this:

public static InputStream findManifest(final Class<?> clazz) throws IOException,
    URISyntaxException{
    final URL jarUrl =
        clazz.getProtectionDomain().getCodeSource().getLocation();
    final JarFile jf = new JarFile(new File(jarUrl.toURI()));
    final ZipEntry entry = jf.getEntry("META-INF/MANIFEST.MF");
    return entry == null ? null : jf.getInputStream(entry);
}

这篇关于如何从spring实例化的POJO类(不是servlet)中读取manifest.mf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆