Spring MVC 在使用ServletContainerInitializer时,web.xml的标记的等价物是什么< env-entry>?

9rygscc1  于 8个月前  发布在  Spring
关注(0)|答案(3)|浏览(53)

我试图用一个基于代码的类来替换我的web.xml文件,该类扩展自Spring的WebApplicationInitializer。我的web.xml文件有几个“env-entry”元素。我试图弄清楚如何在我的WebApplicationInitializer类中设置这些元素,但没有运气。也许有人知道这些标签的代码等效物?

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        appContext.setConfigLocation("WEB-INF/springmvc-servlet.xml");

        Dynamic servlet = servletContext.addServlet("springmvc", new DispatcherServlet(appContext));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/*");

        //How do I add this?
        //  <env-entry>
        //      <env-entry-name>logback/configuration-resource</env-entry-name>
        //      <env-entry-type>java.lang.String</env-entry-type>
        //      <env-entry-value>logback.xml</env-entry-value>
        //  </env-entry>    
    }
}
2q5ifsrm

2q5ifsrm1#

<env-entry>本质上只是声明了一个web应用程序上下文属性,您可以将自己与已有的ServletContext#setAttribute()绑定

servletContext.setAttribute("logback/configuration-resource", "logback.xml");
s8vozzvw

s8vozzvw2#

接受的答案对我不起作用。过了一段时间,我最终找到了一个解决方案,并将其发布到一个类似的堆栈溢出帖子,并包括在这里,以防它帮助任何一个:
https://stackoverflow.com/a/66109551/2441088

kuhbmx9i

kuhbmx9i3#

截至2023年,web.xml仍在运行,并完美地处理env-entries。而不是使用大型web.xml来引导整个应用程序,只需使用web.xml中与您的需求相关的部分。不要在web.xml中使用metadata-complete=“true”和absolute-ordering,因为它们会干扰classpath扫描。以下web.xml与spring Boot boot完美兼容:

<web-app id="example" version="3.0"
    xmlns:javaee="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <env-entry>
        <description>As an example of env-env usage, let set spring profiles</description>
        <env-entry-name>spring.profiles.active</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>universe</env-entry-value>
    </env-entry>

    <env-entry>
        <description>Answer to the life the universe and everything?</description>
        <env-entry-name>answer</env-entry-name>
        <env-entry-type>java.lang.Long</env-entry-type>
        <env-entry-value>42</env-entry-value>
    </env-entry>

</web-app>

Envivorment条目在spring context中完全可用。

@Configuration
public class UniverseConfiguration {

    @Profile("universe")
    @Value("${answer}")
    Long answer;

}

简而言之,web.xml并没有被弃用和删除。只是ServletInitalizers不再需要它了。在应用程序引导期间,webServer仍然会扫描web.xml。

相关问题