Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet 3.0 Spring Java Config JNDI

I am trying to replicate the resource-ref attribute of web.xml in my spring web apps WebApplicationInitializer to configure JNDI.

How would I do this:

<resource-ref>
<description>Connection Pool</description>
<res-ref-name>jdbc/LocalCheddar</res-ref-name>
<res-type>javax.sql.Datasource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

in java config rather than xml?

like image 796
ctrlspace Avatar asked May 24 '13 06:05

ctrlspace


People also ask

Is Jndi used in spring?

JPA Configuration – Model, DAO and Service. With this, you have everything you need in order to use your JNDI datasource in your Spring application.

What is Java comp ENV?

Context envContext = (Context)initContext.lookup("java:comp/env"); allows defining a variable pointing directly to this node. It allows doing SomeBean s = (SomeBean) envContext.lookup("ejb/someBean"); DataSource ds = (DataSource) envContext.lookup("jdbc/dataSource"); rather than. SomeBean s = (SomeBean) initContext.


1 Answers

Looking into the spec for servlet 3.0 I found the @Resource annotation. Instead of in my WebApplicationInitializer class it's now in my WebConfig class.

@Bean
@Resource(name="jdbc/MyDB")
public DataSource dataSourceLookup() {
    final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
    dsLookup.setResourceRef(true);
    DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/MyDB");
    return dataSource;
}
like image 55
ctrlspace Avatar answered Oct 02 '22 23:10

ctrlspace