How do you get current active/default Environment profile programmatically in Spring?

前端 未结 6 932
梦毁少年i
梦毁少年i 2020-11-29 19:17

I need to code different logic based on different current Environment profile. How can you get the current active and default profiles from Spring?

6条回答
  •  没有蜡笔的小新
    2020-11-29 20:11

    Seems there is some demand to be able to access this statically.

    How can I get such thing in static methods in non-spring-managed classes? – Aetherus

    It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment() before all beans have been created, since there is no guarantee when this component will be instantiated.

    @Component
    public class SpringContext
    {
        private static Environment environment;
    
        public SpringContext(Environment environment) {
            SpringContext.environment = environment;
        }
    
        public static Environment getEnvironment() {
            if (environment == null) {
                throw new RuntimeException("Environment has not been set yet");
            }
            return environment;
        }
    }
    

提交回复
热议问题