【发布时间】:2017-03-12 19:59:14
【问题描述】:
我使用 STS 创建了新的 Spring Starter 项目。
在我添加的 pom 文件中:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
然后我创建了 beans.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="databaseService" class="com.pckg.DatabaseService">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="username" value="postgres"/>
<property name="password" value="password"/>
<property name="url" value="jdbc:postgresql://localhost:5432/postgres"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
<qualifier value="transactionManager" />
</bean>
</beans>
并添加到我几乎为空的 web.xml 文件中:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>
我的 DatabaseService 类如下所示:
import org.apache.tomcat.jdbc.pool.DataSource;
...
@Service("databaseService")
@Transactional
public class DatabaseService {
private NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
if (jdbcTemplate == null)
jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public DatabaseService(DataSource dataSource){
this.setDataSource(dataSource);
}
public DatabaseService(){
}
public String getData(){
//jdbcTemplate.query("SELECT 1",.....);
return null;
}
}
我想让这个配置工作。由于某些原因,没有看到这些 bean,我无法启动此应用程序。 我有一个例外:
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE.
那是因为 application.properties 不包含 spring.datasource.driver-class-name=... 条目和我包含在 beans.xml 文件中的其他条目
当我输入该数据并且应用程序启动时,beans.xml 中提供的其他信息将被忽略,我相信这些 bean 都没有被“执行”。我希望 transactionManager 参与我的 SQL 查询,目前这是不可能的。
【问题讨论】:
-
为什么要使用XML而不使用
application.properties?我没有看到任何普通用法无法实现的东西? -
从 application.properties 中的数据创建的 DataSource 没有我放在那里的所有设置,所以我想自己创建一个包含该数据的 bean,我解决了它在 Java 类中使用 @Configuration 创建 bean注释
标签: spring postgresql spring-boot spring-jdbc