Tomcat 8 Embedded - 不赞成使用ContextResource

时间:2016-01-14 06:33:19

标签: java apache tomcat jndi tomcat8

相信你。

我想将嵌入式tomcat源代码从tomcat 7迁移到tomcat 8。 但我对 org.apache.catalina.deploy.ContextResource 有疑问,到目前为止我还不知道其他方式。

我认为在tomcat 8中不推荐使用 org.apache.catalina.deploy

整体源代码:

public class Tomcat8LocalServer {
public static void main(String[] args) {
    String baseDir = (System.getProperty("basedir") == null ? System.getProperty("user.dir") : System
            .getProperty("basedir")) + "/public_html/epi_html";

    Tomcat tomcat = new Tomcat();
    tomcat.enableNaming();
    try {
        Context context = tomcat.addWebapp("/epi", baseDir);

        bindDataSource(context);

        tomcat.getConnector().setPort(Integer.valueOf(System.getProperty("tomcat.embedded.port", "8080")));
    }
    catch (ServletException ex) {
        throw new IllegalStateException("failed to add webapp", ex);
    }

    try {
        long start = System.currentTimeMillis();
        tomcat.start();
        System.out.println("[Tomcat embedded] Server started in " + (System.currentTimeMillis() - start) + " ms");
        System.setProperty("tomcat.embedded.enabled", "true");
    }
    catch (LifecycleException ex) {
        throw new IllegalStateException("failed to start tomcat server", ex);
    }
    tomcat.getServer().await();
}

private static void bindDataSource(Context context) {

     ContextResource res = new ContextResource();

    res.setName("jdbc/EPIZIV_DS");
    res.setType("javax.sql.DataSource");

    res.setProperty("username", System.getProperty("tomcat.embedded.datasource.username", "EPIZIV"));
    res.setProperty("password", System.getProperty("tomcat.embedded.datasource.password", "EPIZIV"));
    res.setProperty("driverClassName",
            System.getProperty("tomcat.embedded.datasource.driver", "oracle.jdbc.OracleDriver"));
    res.setProperty("url",
            System.getProperty("tomcat.embedded.datasource.url", "jdbc:oracle:thin:@localhost:1521:xe"));
    res.setProperty("maxActive", System.getProperty("tomcat.embedded.datasource.max.active", "5"));
    res.setProperty("maxIdle", System.getProperty("tomcat.embedded.datasource.max.idle", "1"));

    context.getNamingResources().addResource(res);
}

StackTrace快照: Stacktrace

我的问题:

  1. 有没有办法替换 org.apache.catalina.deploy.ContextResource
  2. 如何将数据源属性初始化/绑定到嵌入式tomcat 8源代码?

1 个答案:

答案 0 :(得分:1)

ContextResource可以在Tomcat Embedded Core中找到,其包名称应为“org.apache.tomcat.util.descriptor.web”。你可以检查你的导入和类路径吗?