【发布时间】:2021-05-23 12:03:22
【问题描述】:
我正在尝试使用 Spring 4 和数据源配置连接到数据库。 我正在学习教程,所以这是正确的配置:
package spittr.config;
import ...
@Configuration
public class DataConfig {
@Bean
public JndiObjectFactoryBean dataSource() {
JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
jndiObjectFB.setJndiName("java:jboss/datasources/jdbc/SpitterDS");
jndiObjectFB.setProxyInterface(javax.sql.DataSource.class);
return jndiObjectFB;
}
@Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
一切正常,但如您所见,我返回的是 JndiObjectFactoryBean 而不是 Datasource。如果我对 Spring 理解得很好(可能我不理解,否则在这里我会理解),如果你不指定 Bean 名称,Spring 会将 bean 的名称设置为返回类型,第一个字母为小写。 例如,以下代码行将返回一个 id 为“myFantasticBean”的bean(“m”小写)
@Bean
public MyFantasticBean createMyBean() {
return new MyFantasticBean();
}
我在网上看到很多人使用这个版本的 DataConfig,其中方法 dataSource() 返回一个 DataSource 类型的对象(应该是这样):
package spittr.config;
import ...
@Configuration
public class DataConfig {
@Bean
public DataSource dataSource() {
JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
jndiObjectFB.setJndiName("java:jboss/datasources/jdbc/SpitterDS");
jndiObjectFB.setProxyInterface(javax.sql.DataSource.class);
return (DataSource) jndiObjectFB.getObject();
}
@Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
但是如果我使用这个 DataSource 创建,我会得到以下错误:
bin/content/10_SpringWeb_BE_JDBC.war/WEB-INF/classes/spittr/data/JdbcSpitterRepository.class"]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplate' defined in class path resource [spittr/config/DataConfig.class]: Bean instantia
tion via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jdbc.core.JdbcOperations]: Factory method 'jdbcTemplate' threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
我什至找到了解决方案,修改了 dataSource() 方法,现在变成了这样:
package spittr.config;
import ...
@Configuration
public class DataConfig {
@Bean
public DataSource dataSource(){
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
DataSource dataSource = dsLookup.getDataSource("java:jboss/datasources/jdbc/SpitterDS");
return dataSource;
}
@Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
但我真的不明白为什么这行得通,而以前的行不通。有人可以向我解释我做错了什么吗?
非常感谢
【问题讨论】:
标签: java spring datasource jndi jdbctemplate