gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:34:11 25 4
gpt4 key购买 nike

当我们使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com