如何将 JAX-RS REST-Service 与 JNDI 查找集成到 SpringBoot 中?

How to integrate a JAX-RS REST-Service with a JNDI lookup into SpringBoot?

我有一个简单的 jax-rs REST 服务,它作为 WAR 部署在 wildfly 服务器上,并使用 JNDI 查找 standalone.xml 中配置的数据源。为此,路径是从 datasource.properties 文件中读取的。该服务然后通过此数据源执行数据库操作。

现在我想在部署到嵌入式 tomcat 的 SpringBoot 应用程序中使用此 REST 服务。我的实现使用 RESTEasy,该服务可以很容易地与 resteasy-spring-boot-starter 集成。但是 JNDI 查找不起作用,因为当然数据源现在没有配置在 standalone.xml 中,而是在 application.properties 文件中。它是一个完全不同的数据源。

我正在寻找无需 "hard code" 即可设置数据源的解决方案。这是当前在 WAR 中为 wildfly 检索连接的方式:

private Connection getConnection() {

    Connection connection = null;

    try (InputStream config = OutboxRestServiceJbossImpl.class.getClassLoader().getResourceAsStream("application.properties")) {

        Properties properties = new Properties();
        properties.load(config);
        DataSource ds = (DataSource) new InitialContext().lookup(properties.getProperty("datasource"));
        connection = ds.getConnection();

    } catch (Exception e) {

    }

    return connection;
}

目前,我通过拥有一个核心模块来解决这个问题,该模块实际执行逻辑,并在 SpringBoot 中使用 jax-rs for wildfly 和 SpringMVC 实现 2 个实现。它们调用核心模块实例的方法,并将连接移交给这些方法。对于野蝇来说,这看起来像这样:

public String getHelloWorld() {


    RestServiceCoreImpl rsc = new RestServiceCoreImpl();

    try (Connection connection = getConnection()) {

        String helloWorld  = rsc.getHelloWorld(connection);

    } catch (Exception e) {

    }
    return helloWorld;
}


public String getHelloWorld(Connection connection){

//database stuff, eg. connection.execute(SQL);
}

在 SpringBoot 中像这样:

@Autowired
RestServiceCoreImpl rsc;

@Autowired
DataSource restServiceDataSource;

@Override
public String getHelloWorld() {

    try (Connection connection = restServiceDataSource.getConnection()){
        return rsc.getHelloWorld(connection);

    } catch (SQLException e) {

    }

    return null;
}

有什么办法可以解决这个数据源问题吗?我需要将 SpringMVC 解决方案替换为 SpringBoot 中的 jax-rs 解决方案。

好的,我自己解决了这个问题。这是我的解决方案:

我在嵌入式 tomcat 服务器中启用了如下命名:

@Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
    @Override
    protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
        tomcat.enableNaming(); 
        return super.getTomcatWebServer(tomcat);
    }

然后我能够在服务器上下文中添加 JNDI 资源。现在可以进行 JNDI 查找了。