在我们的 Spring 4 应用程序中,我们当前在 applicationContext.xml 中配置数据库连接:
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
<property name="maximumPoolSize" value="10" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="url">jdbc:postgresql://google/mydb?cloudSqlInstance=project:region:myinstance&socketFactory=com.google.cloud.sql.postgres.SocketFactory</prop>
<prop key="user">postgres</prop>
<prop key="password">password</prop>
</props>
</property>
</bean>
我可以在如下类中定义数据库配置,而不是在 applicationContext.xml 中定义它:
HikariConfig config = new HikariConfig();
config.setJdbcUrl(JDBC_URL);
config.setUsername(DB_USER);
config.setPassword(DB_PASS);
....
可以这样做吗?
最佳答案
您可以在 HikariDataSource 上定义属性
public DataSource getDataSource(){
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(JDBC_URL);
dataSource.setUsername(DB_USER);
dataSource.setPassword("DB_PASS);
return dataSource;
}
public class HikariDataSource extends HikariConfig implements DataSource, Closeable
然后将您的方法声明为 @Configuration
类中的 @Bean
@Bean
public DataSource dataSource() {
return DataSourceClass.getDataSource();
}
关于java - Spring 4 使用基于类的数据库初始化而不是 xml bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409400/