简体   繁体   English

如何在Spring Boot XML文件中注册servlet?

[英]How to register a servlet in Spring Boot XML file?

I wrote a servlet for a Spring Boot application. 我为Spring Boot应用程序编写了一个servlet。 It worked when I used 我用的时候很有效

contextHandler.addServlet(MyClass.class, "/v1/route");

Now I'm trying to register the servlet in beans.xml file as a bean. 现在我正在尝试将beans.xml文件中的servlet注册为bean。 This one 这个

<bean id="myId" class="com.abc.MyClass"/>

doesn't contain route. 不包含路线。 MyClass extends HttpServlet and overrides doGet method. MyClass扩展了HttpServlet并覆盖了doGet方法。

How to register a servlet which is also a bean? 如何注册一个也是bean的servlet?

This approach worked for me. 这种方法对我有用。 It's a mix of declaration in XML and a fully programmatic registration. 它是XML声明和完全程序化注册的混合体。

In beans.xml file I've specified a constructor parameter which passed ServletContextHandler, like this: 在beans.xml文件中,我已经指定了一个传递ServletContextHandler的构造函数参数,如下所示:

<bean id="myId" class="com.abc.MyClass">
    <constructor-arg ref="servletContextHandler"/>
</bean>

In MyClass constructor I'm adding the servlet - together with route - to the servlet holder, thus registering it as servlet: 在MyClass构造函数中,我将servlet与route一起添加到servlet持有者,从而将其注册为servlet:

public MyClass(ServletContextHandler h) {
    h.addServlet(new ServletHolder(this), "/v1/route");
}

Surely this can interfere with other requirements, like the constructor may need other parameters, other initializations may be needed. 当然这可能会干扰其他要求,比如构造函数可能需要其他参数,可能还需要其他初始化。 But here I'm registering a bean in XML and registering servlet programmatically. 但是在这里我正在用XML注册bean并以编程方式注册servlet。 May be the servlet registration can also be done without explicit Java code, I don't know how to do that. 可能是servlet注册也可以在没有显式Java代码的情况下完成,我不知道该怎么做。

xerx593, I've seen that page but those examples didn't look good enough for what I wanted. xerx593,我看过那个页面,但那些例子对我想要的东西看起来不够好。 Thank you anyway. 还是要谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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