java - 以编程方式为 Spring 创建 JNDI 数据源

标签 java spring mocking jndi initial-context

我有一个现有的基于 Spring Web 的应用程序,它具有使用 JNDI 定义的数据源,我正在尝试创建一个独立的应用程序来使用这些 bean。如何在独立应用程序中以编程方式创建 JNDI 条目和数据库属性?

<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/MyDS" />
</bean>

    public static void main(String[] args) {

      // this throws an error since the JNDI lookup fails - can I programmatically define the database properties here?

    ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");

    UserService userService = ctx.getBean(UserService.class);
    User user = userService.findUserById("jdoe");

    System.out.println("display name: " + user.getDisplayName());
}

编辑:

我试过类似的方法,但现在收到错误“javax.naming.NoInitialContextException:需要在环境或系统属性中指定类名”

public static void main(String[] args) {
    setupJNDI();

    ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");

    UserService userService = ctx.getBean(UserService.class);
    User user = userService.findUserById("jdoe");

    System.out.println("display name: " + user.getDisplayName());
}


private static void setupJNDI() {
    InitialContext ic;
    try {
        ic = new InitialContext();
        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");
        SQLServerConnectionPoolDataSource myDS = new SQLServerConnectionPoolDataSource();
        opaDS.setServerName("myserver");
        opaDS.setPortNumber(1433);
        opaDS.setUser("user");
        opaDS.setPassword("password");

        ic.bind("java:/comp/env/jdbc/MyDS", myDS);
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

最佳答案

org.springframework.test 依赖项通过 SimpleNamingContextBuilder 支持它:

// First create the mock JNDI tree and bind the DS
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
DataSource ds = new ComboPooledDataSource();
ds.setDriverClass( ... ); // etc. for uid, password, url
builder.bind( "java:comp/env/jdbc/MyDS" , ds );
builder.activate();

// Then create the Spring context, which should now be able 
// to resolve the JNDI datasource
ApplicationContext context = new ClassPathXmlApplicationContext( "..." );

这应该有效。

干杯,

关于java - 以编程方式为 Spring 创建 JNDI 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14982125/

相关文章:

java - ActiveProfile 在 Junit5 测试中不起作用

java - JMH 就像禁用方法内联 - 它是如何完成的?

java - 如果 main() 只启动另一个带有计时器作业的线程,那么 main() 该怎么办?

java - JPA - 多对一,其中子级具有父级 ID

go - 你如何在 GoLang 的模拟中模拟错误返回值?

ruby-on-rails - 在 Rspec 中使用数据库查询好不好?

java - 验证日期 - Bean 验证注释 - 具有特定格式

java - ORA-02289 : sequence does not exist - when using Spring Data JPA with Spring boot

java - 野蝇spring项目部署

unit-testing - 为什么在 goroutine 中声明时 benbjohnson/clock 模拟计时器不执行?