我有一个简单的jax-rs REST服务,该服务作为WAR部署在Wildfly服务器上,并使用JNDI查找在standalone.xml中配置的数据源。为此,将从datasource.properties文件读取路径。然后,该服务通过该数据源执行数据库操作。
现在,我想在部署到嵌入式tomcat的SpringBoot应用程序中使用此REST服务。我的实现使用RESTEasy,该服务可以轻松地与resteasy-spring-boot-starter集成。但是JNDI查找不起作用,因为现在当然不是在standalone.xml中而是在application.properties文件中配置了数据源。这是一个完全不同的数据源。
我正在寻找一种解决方案来设置数据源,而不必对其进行“硬编码”。这是当前在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中为wildfly和SpringMVC使用jax-rs执行逻辑和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解决方案。