How to convert jndi search from xml to java config

I am currently converting xml to java config. But I was stuck in some part that I spent for several days. Here's the problem:

Xml config:

<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> 

So far I have managed to convert this code:

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

:

 @Bean(name = "dbDataSource") public JndiObjectFactoryBean dataSource() { JndiObjectFactoryBean bean = new JndiObjectFactoryBean(); bean.setJndiName("${db.jndi}"); bean.setResourceRef(true); return bean; } 

And this:

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

:

 @Bean(name = "jdbcTemplate") public JdbcTemplate jdbcTemplate() { JdbcTemplate jt = new JdbcTemplate(); jt.setDataSource(dataSource); return jt; } 

The problem is that the setDataSource () method needs a DataSource object, but I'm not sure how to bind as a bean. How to pass JndiObjectFactoryBean to DataSource?

Or do I need to use a different method?

Additional question:

bean.setJndiName("${db.jndi}") , $ {db.jndi} refers to the properties file, but I always got a NameNotFoundException, how to make it work?

Thanks!!

+6
source share
1 answer

Instead of JndiObjectFactoryBean , use JndiDataSourceLookup . To use ${db.jndi} in a method, declare the method argument and annotate it with @Value .

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

Auto-updated methods and constructors can also use the @Value annotation. - Spring Reference Guide.

@Bean methods are basically factory methods, which are also automatic wire methods and as such fall into this category.

In your factory method for JdbcTemplate you can simply use the argument of the DataSource method to get a reference to the data source (if you have several, you can use @Qualifier in the argument of the method to indicate which one you want to use).

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

All Articles