簡體   English   中英

使用spring EL獲取Spring配置文件名稱

[英]Get Spring profile name with spring EL

考慮一個帶有spring 4的基於Web的應用程序。spring bean配置文件在web.xml中定義,如下所示:

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

現在考慮在spring-applicaiton-context.xml中將bean定義為

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

是否可以訪問活動配置文件列表並選擇第二個配置文件(在我的示例edb中)。 這樣,當活動配置文件更改時,我可以動態地加載資源。


這可能會有所幫助! 當Web應用程序以以下代碼開頭時,我可以獲取活動配置文件:

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

語法為"#{environment.activeProfiles[1]}" -但是,在上下文生命周期中為時尚早。 在這種情況下,在評估SpEL之前未設置activeProfiles。

怎么了

<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>

其實我才發現

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

有效-顯式調用getter會導致加載屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM