如何将JAX-RSREST服务与JNDI查找集成到SpringBoot中



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

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

我正在寻找一种解决方案来设置数据源,而不必对其进行"硬编码">

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。它们调用核心模块实例的方法,然后将连接移交给这些方法。这看起来像是野生苍蝇:

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查找了。

最新更新