如何将jndi查找从xml转换为java config [英] how to convert jndi lookup from xml to java config
问题描述
当前,我正在将xml转换为java config.但是我坚持研究了几天.问题出在这里:
Currently I'm converting the xml to java config. But I stuck at some part that I have been research for several days. Here the problem:
Xml配置:
<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 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;
}
这:
<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;
}
问题在于方法 setDataSource()需要DataSource对象,但是我不确定如何将两个bean关联起来.如何将JndiObjectFactoryBean传递给DataSource?
The problem is the method setDataSource() need DataSource object but I'm not sure how to relate both bean.How to pass the JndiObjectFactoryBean to DataSource?
还是我需要使用其他方法?
Or do I need to use another method?
其他问题:
bean.setJndiName("${db.jndi}")
, $ {db.jndi} 是引用属性文件,但我总是得到NameNotFoundException,如何使其工作?
The bean.setJndiName("${db.jndi}")
, ${db.jndi} is refer to properties file but I always got NameNotFoundException, How to make it work?
谢谢!
推荐答案
使用JndiDataSourceLookup
代替JndiObjectFactoryBean
.要在方法中使用${db.jndi}
,请声明一个方法参数并用@Value
对其进行注释.
Instead of JndiObjectFactoryBean
use a JndiDataSourceLookup
instead. To use the ${db.jndi}
in the method declare a 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);
}
自动装配的方法和构造函数也可以使用
@Value
批注. -Spring参考指南.
Autowired methods and constructors can also use the
@Value
annotation. -- Spring Reference Guide.
@Bean
方法基本上是工厂方法,也是自动连接方法,因此属于此类.
@Bean
methods are basically factory methods which are also auto wired methods and as such fall into this category.
在用于JdbcTemplate
的工厂方法中,您可以简单地使用DataSource
方法参数来获取对数据源的引用(如果有多个,则可以在方法参数上使用@Qualifier
来指定要使用哪个要使用).
In your factory method for the JdbcTemplate
you can simply use a DataSource
method argument to get a reference to the datasource (If you have multiple you can use the @Qualifier
on the method argument to specify which one you want to use).
@Bean
public JdbcTemplate jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
这篇关于如何将jndi查找从xml转换为java config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!