java - spring jdbc中数据源是否需要在原型(prototype)范围内

标签 java spring spring-mvc spring-jdbc jdbctemplate

当我们使用spring jdbc时,首先我们定义一个dataSource bean并在创建jdbcTemplate对象时注入(inject)它。我想知道的是我们是否需要在原型(prototype)范围内定义这个数据源。除非整个应用程序只有一个数据源对象。我认为这会降低应用程序性能。

这是我在 spring 配置文件中定义 dataSouce 的方式。

<bean id="dataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="username" value="root" />
<property name="password" value="123" />
</bean> 

在我的 DAO 类中,我 Autowiring 了 dataSOurce,如下所示。

@Repository
public class RecordDAOImpl {

JdbcTemplate jdbcTemplate = null;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

}

让我知道为 spring mvc web 应用程序定义数据源的最佳方法是什么。

最佳答案

What I want to know is do we need to define this dataSource in prototype scope

不,我们不需要。我想这不是个好主意,我们可以使用某种连接池数据源和单例作用域 bean。

我们也可以有多个数据库,并为每个数据源提供单例范围,这没有任何问题。

Let me know what is the best way to define dataSource for spring mvc web application.

在 xml 文件中定义数据源并没有错(尽管许多开发人员似乎避免使用 xml)。我喜欢使用 java 配置来完成它,因为我觉得它更容易阅读。

根据驱动程序和数据库,它看起来或多或少像这样:

@Configuration
class DatasourceConfig {

    @Bean
    DataSource datasource() {
        PGPoolingDataSource dataSource = new PGPoolingDataSource();
        dataSource.setPassword("pass");
        dataSource.setPortNumber(123);
        dataSource.setUser("user");
        dataSource.setMaxConnections(10);
        return dataSource;
    }
}

关于java - spring jdbc中数据源是否需要在原型(prototype)范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42456378/

相关文章:

java - 通过构造函数实例化 Bean 失败;嵌套异常是 org.springframework.beans.BeanInstantiationException

java - Spring Boot 测试 : Test Response throws "Could not find acceptable representation" , App 正常运行

java - 子流调用在 Spring webflow 中不起作用

java - 400 错误请求 - 将 JSON 数据发布到使用 Spring MVC 实现的 RESTful Controller 时

java - Java 2D 图形中的 "Screen"效果

Spring security的Java配置不识别/j_spring_security_check

java - 如何覆盖 Spring Boot 2.0.x 中的默认连接池限制

java - 如何在 spring 中将模型作为重定向属性传递

java - PDFBox 设置覆盖特定页面

java - Android:ListViews 和 CheckBoxes 的问题