Get Spring profile name with spring EL

 ̄綄美尐妖づ 提交于 2019-12-07 16:34:42

问题


Consider a web based application with spring 4. The spring bean profiles is defined in web.xml like:

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>prod,edb,cas</param-value>
</context-param>

Now consider a bean is defined in spring-applicaiton-context.xml as

<util:properties id="myPolicy"      
    location=
      "classpath:/configs/${ACCESS-ACTIVE-PROFILE-SECOND-ITEM}/my-policy.properties" />

Is it possible that I can access the list of active profiles and select the second one (in my example edb). In this way I can make my resource load dynamically when active profile changes.


This may help! I could get the active profile when web application starts with below code:

    public void contextInitialized(ServletContextEvent event){
        ApplicationContext applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(event.getServletContext());
        String activeProfiles[] = applicationContext.getEnvironment().getActiveProfiles();
        system.out.print(activeProfiles[1])
    }

回答1:


The syntax would be "#{environment.activeProfiles[1]}" - however, it's too early in the context life cycle; the activeProfiles is not set up before the SpEL is evaluated in this case.

What's wrong with

<beans profile="foo">
    <util:properties id="myPolicy" 
          location="classpath:/configs/foo/my-policy.properties" />
</beans>

<beans profile="bar">
    <util:properties id="myPolicy" 
          location="classpath:/configs/bar/my-policy.properties" />
</beans>

?

Actually, I just found that

"#{environment.getActiveProfiles()[1]}"

works - explicitly calling the getter causes the property to be loaded.



来源:https://stackoverflow.com/questions/33449014/get-spring-profile-name-with-spring-el

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!