【问题标题】:Spring 4.1x, SimpleNamingContextBuilder and @Value("#{environment.xxx}")Spring 4.1x、SimpleNamingContextBuilder 和 @Value("#{environment.xxx}")
【发布时间】:2018-01-26 13:03:50
【问题描述】:

到目前为止,我一直在使用 Spring 4.0.8,以下工作正常:

在我的单元测试中,我在 jndi 环境中输入了一个值:

SimpleNamingContextBuilder _simpleNamingContextBuilder =
        new SimpleNamingContextBuilder();
_simpleNamingContextBuilder.bind(
            "java:comp/env/myBoolVar", true);
_simpleNamingContextBuilder.activate();

然后在我的课堂上,我像这样访问它:

@Value("#{environment.myBoolVar}")
private Boolean _myBoolVar = Boolean.FALSE;

我已升级到 Spring 4.1.2,但不再有效。始终使用默认值 false,因为 Spring 无法找到该值。

如果我使用 old 方式访问这个值:

@Resource(mappedName = "java:comp/env/myBoolVar")

确实有效。

我一直在搜索 SO 和整个网络,我看到了大量的信息,但没有一个信息可以帮助我解决问题。我的理解是 Spring Environment 可以访问 @Value 所做的所有值。所以我不确定是什么问题。

【问题讨论】:

    标签: spring-mvc jndi propertyconfigurator


    【解决方案1】:

    仅供任何在这方面苦苦挣扎的人参考。最后,我将添加“myBoolVar”值到 SimpleNamingContextBuilder 的代码放在带有 @BeforeClass 注释的方法中,现在它可以正常工作了。

    基本上发生的事情是,在启动时,Spring 尝试在 StandardServletEnvironment.customizePropertySources() 方法中整理出它拥有的 PropertySources。当需要查找 jndiProperties 时,它会执行以下操作:

    if(JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
            propertySources.addLast(new JndiPropertySource("jndiProperties"));
        }
    

    JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable() 方法执行以下操作:

    try {
                new InitialContext().getEnvironment();
                return true;
            }
            catch (Throwable ex) {
                return false;
            }
    

    在我的情况下,对 getEnvironment() 的调用引发了 NoInitialContextException:

    javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial 
    

    这阻止了 Spring 创建 jndiProperties PropertySource,因此我的布尔变量丢失了。

    所以我开始在网上寻找为什么会发生这种情况......但后来在 Spring 论坛上发现了一个 old article,说这将我的代码放在了 @BeforeClass 块中,等等。

    我希望这可以在将来的某个时间为某人节省一些痛苦和痛苦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 2017-01-20
      • 1970-01-01
      相关资源
      最近更新 更多