1

我编写了Bootstrapper一个从类路径读取 XML 文件的类,并且可以在运行时被其他类用作轻量级依赖注入器:

<!-- myAppConfig.xml -->
<appConfig>
    <environment runningOn="LOCAL" host="localhost.example.com" system="Windows 7"/>
</appConfig>

public class Bootstrapper
{
    private String runningOn = "Unknown";
    private String host = "Unknown";
    private String system = "Unknown";

    public Bootstrapper(final String appConfigFileName)
    {
        setRunningOn(extractRunningOn(appConfigFileName));
        setHost(extractHost(appConfigFileName));
        setSystem(extractSystem(appConfigFileName));
    }

    public String getHost()
    {
        return host;
    }

    // Rest of class ommitted for brevity...
}

// Then in an executable JAR's main method:
public static void main(String[] args)
{
    Bootstrapper bootstrapper = new Bootstrapper("myAppConfig.xml");

    // Prints: "This app is running on the localhost.example.com server node."
    System.out.println("This app is running on the " +
        bootstrapper.getHost() + " server node.");
}

从这个意义上说appConfigBootstrapper作为轻量级“DI”机制。

我想知道的是:如何将此设计转换为 WAR 的 web.xml 和 EAR 的 server.xml?

而在可执行 JAR 中,该main方法显式实例化 a Bootstrapper,然后可以查询其字段/属性,而在 WAR/EAR 中,所有内容都在 XML 文件 ( web.xml/ server.xml) 中定义,没有单个“入口点”。因此,在 WAR 或 EAR 中,如果我有多个类,每个类都需要知道本地主机名是什么,我将不得不Bootstrapper一遍又一遍地实例化相同的类,每次都传递相同的内容myAppConfig.xml

我想知道是否有一种方法可以配置 web.xml 和 server.xml 以Bootstrapper在启动/部署时实例化一个,并在那时和那里自动注入/填充我的依赖类(或者,至少,给每个依赖类访问BootstrapperXML 文件中定义的全局/单例)。

提前致谢!

4

1 回答 1

1

对于战争(以及耳朵,因为它将包含战争)项目,您可以使用 ServletContextListener 来实例化您的引导程序。

此处是如何使用 ServletContextListener 的一个很好的示例。

但是,如果您使用的是 Java EE 6,那么更好的方法是使用 EJB 3.1 Singleton 和一些 CDI。

import javax.ejb.Singleton
import javax.ejb.Startup
import javax.enterprise.context.ApplicationScoped

@Singleton         // EJB 3.1 Singleton
@Startup           // Telling the container to eagerly load on startup
@ApplicationScoped // CDI Scope
public class Bootstrapper {

    private String host = "Unknown";

    @PostConstruct
    public void readConfiguration() {
        // ... load your xml file
    }

    public String getHost() {
        return host;
    }
}

使用上述内容,您现在可以使用简单的@Inject 或@EJB 注释在大多数EE 6 生态系统中注入这个Bootstrapper bean。

于 2012-05-01T07:59:54.860 回答