【问题标题】:How to integrate a JAX-RS REST-Service with a JNDI lookup into SpringBoot?如何将 JAX-RS REST-Service 与 JNDI 查找集成到 SpringBoot 中?
【发布时间】:2023-03-08 00:39:01
【问题描述】:

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

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

我正在寻找一种无需“硬编码”即可设置数据源的解决方案。这是野蝇当前在 WAR 中检索连接的方式:

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 为 wildfly 和 SpringMVC 实际执行逻辑和 2 个实现的核心模块解决了这个问题。它们调用核心模块实例的方法,并将连接移交给这些方法。 Wildfly 看起来像这样:

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 解决方案。

【问题讨论】:

    标签: rest spring-boot jersey jax-rs resteasy


    【解决方案1】:

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

    我在嵌入式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 查找了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多