How to pass spring boot argument to tomcat deployment?

后端 未结 1 469
终归单人心
终归单人心 2021-01-13 13:41

I have a spring boot project with packaging war stated in the pom file.

war   
...

    org.s         


        
相关标签:
1条回答
  • 2021-01-13 14:17

    You can pass context parameters to the servlet context with a context.xml. Add this as context.xml next to your pom:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE Context>
    <Context>
        <Parameter
            name="spring.profiles.active"
            value="${spring.profiles.active}"
            override="false" />
    </Context>
    

    Then use the maven-war-plugin like this

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
            <containerConfigXML>context.xml</containerConfigXML>
            <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
        </configuration>
    </plugin>
    

    Then use a profile to set the spring.profiles.active property. Spring actually will pick these up without config but somehow Spring Boot does not. For it to work in Spring Boot you can use something like this:

    package com.example;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.context.web.SpringBootServletInitializer;
    
    @SpringBootApplication
    public class DemoApplication extends SpringBootServletInitializer {
    
        private ServletContext servletContext;
    
        @Override
        protected SpringApplicationBuilder configure(
                SpringApplicationBuilder builder) {
            String activeProfiles =
                    servletContext.getInitParameter("spring.profiles.active");
            if (activeProfiles != null) {
                builder.profiles(activeProfiles.split(","));
            }
            return builder.sources(DemoApplication.class);
        }
    
        @Override
        public void onStartup(ServletContext servletContext)
                throws ServletException {
            this.servletContext = servletContext;
            super.onStartup(servletContext);
        }
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题