1

I'm currently using Spring @Profile to manage my web application's configuration based on the environment (DEV, TEST, PROD). In order to activate the right profile, I prefer not to hardcode the value for spring.profiles.active in web.xml. Rather, I want to rely on the JNDI from the server to determine the right profile to activate. I'm able to get this working by creating a JNDI string called spring.profiles.active with the value, say DEV, to activate the DEV profile in my web application.

The problem is my server environment already has a custom JNDI ( say, bla/environment ) that contains the value DEV, TEST or PROD.

Is it possible to set spring.profiles.active based on this custom JNDI so that I don't have to create another JNDI that does the same thing?

Thank you.

4

3 回答 3

3

您始终可以为指向bla/environment. 如何执行此操作取决于您的应用程序服务器。

如果这不可行,您始终可以实现自定义ApplicationContextInitializer(自 Spring 3.1 起可用)。然后这将读取自定义 jndi 条目并设置活动环境。

public class EnvironmentApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private final JndiLocatorDelegate jndi = JndiLocatorDelegate.createDefaultResourceRefLocator();

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        String profile = jndi.lookup("bla/environment", String.class); 
        applicationContext.getEnvironment().addActiveProfile(profile);
    }
}

类似的东西,你将它包装在 a 中try/catch,这样如果条目不存在,应用程序不会失败,而只是依赖于默认机制。

您需要在 web.xml 中添加一个条目以激活它(或者DispatcherServlet如果您想在其中使用它,则将其作为 init-param 添加到 )。

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>your.package.here.EnvironmentApplicationContextInitializer</param-value>
</context-param>
于 2013-10-08T08:51:16.487 回答
0

bla/environment为配置文件 JNDI 条目 ( )创建一个特定于应用程序的别名。有关详细信息,请查看此问题的已接受答案。

于 2013-10-07T21:59:26.337 回答
0

没试过,但我想你可以

<bean id="currentProfileName" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/bla/environment"/>
</bean>

然后把它作为弹簧活动配置文件

<bean
   class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
   <property name="targetClass" value="java.lang.System" />
   <property name="targetMethod" value="setProperty" />
   <property name="arguments">
    <list>
        <value>spring.profiles.active</value>
        <ref bean="currentProfileName" />
    </list>
   </property>
</bean>
于 2013-10-07T21:38:08.817 回答