简体   繁体   中英

How to read war-file manifest in its jar-dependency?

How do I read the war -file manifest property in its jar -dependency?

UPD: servlets are not used here (it's spring-bean initialization code).

Since a .war file's purpose is to handle servlets, I assume all of your code is called from servlets, or from a technology built on servlets, like JSP, JSF, or even Spring.

Call the current request's getServletContext() method , and use the getResource or getResourceAsStream method of ServletContext. Those methods work just like the same methods of java.lang.Class, only they look in the .war file itself before searching the web application's classpath for a matching path.

For example:

public Optional<Manifest> getWarManifest(ServletRequest request)
throws IOException {

    InputStream manifest =
        request.getServletContext().getResourceAsStream(
            "/META-INF/MANIFEST.MF");

    if (manifest == null) {
        return Optional.empty();
    }

    try (InputStream stream = new BufferedInputStream(manifest)) {
        return Optional.of(new Manifest(stream));
    }
}

Update:

Since you want to read the manifest when preparing a Spring bean, it appears you can autowire a ServletContext object :

@Configuration
public class MyAppConfig {
    @Bean
    public MyBean createMyBean(@Autowired ServletContext context)
    throws IOException {

        Optional<Manifest> manifest;

        InputStream source =
            context.getResourceAsStream("/META-INF/MANIFEST.MF");

        if (source == null) {
            manifest = Optional.empty();
        } else {
            try (InputStream stream = new BufferedInputStream(source)) {
                manifest = Optional.of(new Manifest(stream));
            }
        }

        return new MyBean(manifest);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM