Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weblogic jndi NameNotFoundException occur with java config

I been searching again for this issue where I cannot locate the jndi database by using java config. Before this I use xml and its work perfectly but in java config it cause an issue;

Xml code:

     <!-- Jndi database connection -->
     <jee:jndi-lookup id="dbDataSource" jndi-name="${db.jndi}"
     resource-ref="true" />

     <beans:bean id="jdbcTemplate"
     class="org.springframework.jdbc.core.JdbcTemplate" >
     <beans:property name="dataSource" ref="dbDataSource"></beans:property>
     </beans:bean>

Java config now:

@Bean(name = "dbDataSource")
public DataSource dataSource(@Value("${db.jndi}") String jndiName) 
{
    JndiDataSourceLookup lookup = new JndiDataSourceLookup();
    return lookup.getDataSource(jndiName);
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource ds) { 
    return new JdbcTemplate(ds);
}

Properties file:

db.jndi=jndi/myData

JNDI name in weblogic:

jndi/myData

After change to java config, sometimes the system can read the database but rarely occur, until I clean and restart my computer then it can find the database, but usually its always trigger:

javax.naming.NameNotFoundException: Unable to resolve 'jndi.myData'. Resolved 'jndi'; remaining name 'myData'

Why the application cannot find the database correctly? Thanks!!!

like image 591
FreezY Avatar asked Sep 12 '25 09:09

FreezY


1 Answers

I've had the same issue. If you're using 4.x version of spring that's probably the cause.

You should also check Weblogic's JNDI Tree. If your data source disapears from the tree after rebuilding the project, that's another symptom

If that's the case, what's happening is:

Your Datasource implements Closeable (and therefore AutoCloseable) and the context will always invoke the shutdown method regardless of your Bean definition

as seen here : SPR-12551: Document how to prevent a JNDI DataSource retrieved using JavaConfig to be removed on shutdown of the context

It's been marked as a documentation issue as this is the "expected" behaviour:

This issue was solely about documentation since we decided not to implement anything at the framework level

the solution, is to define the destroy method of the bean as empty, such as:

@Bean(name = "dbDataSource", destroyMethod="")
   public DataSource dataSource(@Value("${db.jndi}") String jndiName) 
{
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
   return lookup.getDataSource(jndiName);
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource ds) { 
   return new JdbcTemplate(ds);
}

This is described in this issue (SPR-13022:Destroy callback cannot be disabled for AutoCloseable beans) .

PS: By the way, it seems like on early 4.x version of spring you couldn't override this behaviour by assingning destroyMethod. It apears that this bug was fixed on version 4.2 RC1.

like image 102
Tiago Nobrega Avatar answered Sep 14 '25 00:09

Tiago Nobrega