How to set Spring profile from system variable?

前端 未结 7 1540
无人共我
无人共我 2020-12-07 18:12

I have a Spring project which uses another project. Each project has its own spring profile initialize from java code using applicationContext.xml and *.p

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 18:50

    I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.

    *Answering your question, system variable has higher priority *


    Getting profile based beans from applicationContext

    • Use @Profile on a Bean

    @Component
    @Profile("dev")
    public class DatasourceConfigForDev
    

    Now, the profile is dev

    Note : if the Profile is given as @Profile("!dev") then the profile will exclude dev and be for all others.

    • Use profiles attribute in XML

    
        
    
    

    Set the value for profile:

    • Programmatically via WebApplicationInitializer interface

      In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically
    @Configuration
    public class MyWebApplicationInitializer implements WebApplicationInitializer {
    
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
                servletContext.setInitParameter("spring.profiles.active", "dev");
        }
    }
    
    • Programmatically via ConfigurableEnvironment

      You can also set profiles directly on the environment:
        @Autowired
        private ConfigurableEnvironment env;
    
        // ...
    
        env.setActiveProfiles("dev");
    
    • Context Parameter in web.xml

      profiles can be activated in the web.xml of the web application as well, using a context parameter:
        
            contextConfigLocation
            /WEB-INF/app-config.xml
        
        
            spring.profiles.active
            dev
        
    
    • JVM System Parameter

      The profile names passed as the parameter will be activated during application start-up:

      -Dspring.profiles.active=dev
      

      In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:

    • Environment Variable

      to set via command line : export spring_profiles_active=dev

    Any bean that does not specify a profile belongs to “default” profile.


    The priority order is :

    1. Context parameter in web.xml
    2. WebApplicationInitializer
    3. JVM System parameter
    4. Environment variable

提交回复
热议问题