Benny
Benny

Reputation: 1465

Spring Boot JNDI resource-ref

I need to declare a resource-ref in a Spring Boot application that will be deployed as war file. This is needed in order to access the database. In traditional webapps, this is added to the web.xml. How can I achieve this in a Spring Boot way?

Thanks, Benjamin

Upvotes: 5

Views: 4900

Answers (1)

Benny
Benny

Reputation: 1465

We got that resolved a while back, so I thought, I'd post this here.


src/main/webapp/WEB-INF/web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
  <resource-ref>
    <res-ref-name>jdbc/DefaultDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
  </resource-ref>
</web-app>

src/main/resources/application.yml

spring:
  datasource:
    jndi-name: jdbc/DefaultDB

src/main/java//DataSourceConfiguration.java

@Configuration
public class DataSourceConfiguration {

    @Bean
    @ConditionalOnMissingBean // optional
    public DataSource jndiDataSource(DataSourceProperties properties) {
        InitialContext context = new InitialContext();
        return (DataSource) context.lookup("unmanageddatasource:" + properties.getJndiName());
    }
}

Upvotes: 5

Related Questions