使用ServletContainerInitializer时,web.xml的<env-entry>标签相当于什么?

问题描述 投票:0回答:3

我正在尝试用从 Spring 的 WebApplicationInitializer 扩展的基于代码的类替换我的 web.xml 文件。我的 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>    
    }
}
java spring spring-mvc servlet-3.0 spring-java-config
3个回答
3
投票

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

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

0
投票

接受的答案对我不起作用。一段时间后,我最终找到了一个解决方案,并将其发布到类似的堆栈溢出帖子中,并包含在这里,以防它对任何人有帮助:

https://stackoverflow.com/a/66109551/2441088


0
投票

截至 2023 年,web.xml 仍在运行并完美处理环境条目。 而不是使用大型 web.xml 来增强整个应用程序,只需使用 web.xml 中与您的需求相关的部分即可。不要在 web.xml 中使用metadata-complete="true" 和绝对排序,因为它们会干扰类路径扫描。以下 web.xml 与 Spring 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 上下文中获得。

@Configuration
public class AppConfiguration {

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

}
© www.soinside.com 2019 - 2024. All rights reserved.