为什么有些资源文件放在META-INF目录下 [英] Why some resource files are put under META-INF directory

查看:2322
本文介绍了为什么有些资源文件放在META-INF目录下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么有些资源文件放在JAR的META-INF目录下?我总是将test.properties之类的资源放在root direccory下。将它们放入META-INF有什么好处?

I am wondering why some resources files are put under the META-INF directory in the JAR? I am always put the resources like test.properties under the root diretcory. Any advantage to put them in the META-INF?

推荐答案

许多Java(EE)API都有一个合同,当你把它放入您(或第三方)JAR的 META-INF 文件夹中的特定配置/元数据文件,然后API将自动执行特定于API的作业,例如扫描类,预加载特定类和/或基于元信息执行特定代码。

Lot of Java (EE) APIs have a contract that when you put a specific configuration/metadata file in the META-INF folder of your (or a 3rd party) JAR, then the API will automatically do the API-specific job, such as scanning classes, preloading specific classes and/or executing specific code based on the meta information.

标准Java SE API提供的示例是 ServiceLoader 。其中,JDBC 4.0兼容的驱动程序实现了这一点。这样只需删除JDBC驱动程序JAR文件夹就会在Java应用程序的启动/初始化期间自动加载驱动程序类,而无需任何手动 Class.forName(com.example.Driver) b代码中的行。

An example provided by the standard Java SE API is the ServiceLoader. Among others, the JDBC 4.0 compatible drivers implement this. This way just dropping the JDBC driver JAR file folder will automatically load the driver class during Java application's startup/initialization without the need for any manual Class.forName("com.example.Driver") line in your code.

此外,还有Java EE 6提供的JSF 2.0 API,它在应用程序启动时扫描所有JAR文件的 faces-config.xml META-INF 文件夹中的文件。如果存在,那么它将作为提示扫描整个JAR文件以获取实现JSF特定注释的类,如 @ManagedBean ,以便自动实例化并自动配置。这节省了在整个类路径中扫描所有JAR中数千个类的潜在昂贵工作的时间。在这些API的旧版本中,配置通常由(详细的)XML文件完成。

Further there is also the Java EE 6 provided JSF 2.0 API which scans during application's startup all JAR files for a faces-config.xml file in the META-INF folder. If present, it then will then take it as a hint to scan the entire JAR file for classes implementing the JSF specific annotations like @ManagedBean so that they get auto-instantiated and auto-configured. This saves time in potentially expensive job of scanning thousands of classes in all JARs in the entire classpath. In older versions of those API's the configuration was usually done by (verbose) XML files.

总而言之,主要目标是从代码中保存开发人员和/或配置样板。 JAR的 META-INF 文件夹用于配置文件/提示。一些API确实也将静态文件/资源​​放在那里供自己使用。 META-INF 文件夹也是类路径的一部分,因此类加载器加载这些文件很容易。

All with all, the major goal is to save the developer from code and/or configuration boilerplate. The JAR's META-INF folder is used for configuration files/hints. Some API's indeed also put static files/resources in there for own use. The META-INF folder is also part of the classpath, so the loading of those files by the classloader is easy done.

这篇关于为什么有些资源文件放在META-INF目录下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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