如何在 Spring Boot 中初始化 JndiTemplate

How to initialize a JndiTemplate in Spring Boot

我确信在 Spring 引导中使用 JNDITemplate 时我期望过高,但是当我尝试将对象绑定到 JNDI 上下文时我得到了一个异常。

@Bean
CommandLineRunner initJndi() {
    return (args) -> {
        Properties props = new Properties();
        props.put("mail.smtp.host", "mail.bla.com");
        ... 
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        });

        JndiTemplate template = new JndiTemplate();
        template.bind("Session", session); 
    };
}

例外情况是:

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

该模板没有 JNDI 上下文。但问题是,上下文要怎么提供呢?

背景 我想为 logback smtp appender 配置 javax.mail 会话。 smtp appender 能够使用来自 JNDI 的邮件会话。请参阅 logback SMTPAppender sessionViaJNDI 属性。

异常是因为您没有指定初始上下文工厂。

请查看此处列出的一些提供商 https://docs.oracle.com/cd/A97688_16/generic.903/a97690/jndi.htm#1005621

Spring 有一个 JndiRmiServiceExporter 使 RMI 变得简单,但我认为选择取决于您要完成的具体目标。