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?
JPA Configuration – Model, DAO and Service. With this, you have everything you need in order to use your JNDI datasource in your Spring application.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With