gpt4 book ai didi

java - 带有 Servlet 3.0 的嵌入式 Tomcat - 扫描时如何跳过某些 jar?

转载 作者:行者123 更新时间:2023-11-28 22:13:35 25 4
gpt4 key购买 nike

下面是一个扫描 Servlet 3.0 初始值设定项的嵌入式 Tomcat 服务器的简单方法:

public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);

StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File("web").getAbsolutePath());

//declare an alternate location for your "WEB-INF/classes" dir:
File additionWebInfClasses = new File("target/classes");
VirtualDirContext resources = new VirtualDirContext();
resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses);
ctx.setResources(resources);

tomcat.start();
System.out.println("Started");
tomcat.getServer().await();
}

我知道 catalina.properties 中的属性 tomcat.util.scan.DefaultJarScanner.jarsToSkip 允许您限制扫描哪些 jar 以加快部署时间。我如何将同样的想法合并到此处的嵌入式 Tomcat 代码中?

奖励:有没有一种方法可以指定包含而不是跳过哪些jar?

最佳答案

虽然我没有加载单个 catalina.properties 属性的特定方法,但我发现只需在 Tomcat 容器上下文中重载 JarScanner 本身就足够方便了,如下所示:

答案在 Groovy 中(抱歉,我偷懒了)

public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new TomcatWithFastJarScanner()
tomcat.setPort(8080)

StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File("web").getAbsolutePath())

//declare an alternate location for your "WEB-INF/classes" dir:
VirtualDirContext resources = new VirtualDirContext()
resources.setExtraResourcePaths("/WEB-INF/classes=" + new File("target/classes"))
ctx.setResources(resources)

tomcat.start()
println "Started server on port 8080"
tomcat.getServer().await()
}

private static class TomcatWithFastJarScanner extends Tomcat {
@Override
public void start() throws LifecycleException {
getServer().findServices().each { service ->
service.getContainer().findChildren().each { container ->
container.findChildren().each { c ->
((Context) c).setJarScanner(new FastJarScanner())
}
}
}
super.start()
}
}


private static class FastJarScanner extends StandardJarScanner {
def jarsToInclude = [ 'spring-web.*' ]

@Override
public void scan(ServletContext context, ClassLoader classloader,
JarScannerCallback callback, Set<String> jarsToSkip) {
jarsToSkip = new HashSet<String>();

((URLClassLoader) classloader.getParent()).getURLs().each {
def jar = it.path.find(/[^\/]+\.jar$/)
if(!jar) return
for(String inclusionPattern : jarsToInclude) {
if(jar.find(inclusionPattern))
println "including jar: " + jar
else jarsToSkip.add(jar)
}
}

super.scan(context, classloader, callback, jarsToSkip);
}
}

基本思想是我们查看类加载器可以看到的所有 jar,并排除所有我们不想包含的 jar。

Tomcat 嵌入式启动速度非常快!

关于java - 带有 Servlet 3.0 的嵌入式 Tomcat - 扫描时如何跳过某些 jar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17616431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com