gpt4 book ai didi

java - 如何在 Spring Boot 中手动配置 JdbcTemplate?

转载 作者:行者123 更新时间:2023-11-30 07:53:15 25 4
gpt4 key购买 nike

这是我的基本 DAO 实现类:

@Repository
public class MeetingDaoImpl implements MeetingDao {

@Autowired
JdbcTemplate jdbcTemplate;

public boolean insertNewMeeting(String initials, String meetingId, int numYears) {

int numRowsAffected = jdbcTemplate.update(SQLConstants.INSERT_NEW_MEETING,
new Object[] {initials.toLowerCase(), meetingId, numYears});

return numRowsAffected > 0;

}
}

jdbcTemplate 自动从我的 application.properties 文件中读取 spring.datasource 属性,这很棒,但它包括我的数据库密码这是我不想 promise 的事情。相反,我想从本地 server.properties 文件中读取它,而我可以轻松地从 Java 类中读取它。

有没有办法用 Java 配置 jdbcTemplate?我见过多个使用 bean 和 XML 的示例,但没有一个使用 Java。

最佳答案

只需声明一个JdbcTemplate bean:

@Bean
JdbcTemplate jdbcTemplate() throws IllegalAccessException, InvocationTargetException, InstantiationException {
// extract this 4 parameters using your own logic
final String driverClassName = "org.h2.Driver";
final String jdbcUrl = "jdbc:h2:mem:test";
final String username = "sa";
final String password = "";
// Build dataSource manually:
final Class<?> driverClass = ClassUtils.resolveClassName(driverClassName, this.getClass().getClassLoader());
final Driver driver = (Driver) ClassUtils.getConstructorIfAvailable(driverClass).newInstance();
final DataSource dataSource = new SimpleDriverDataSource(driver, jdbcUrl, username, password);
// or using DataSourceBuilder:
final DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(jdbcUrl).username(username).password(password).build();
// and make the jdbcTemplate
return new JdbcTemplate(dataSource);
}

另一种方法是不在 application.properties 文件中设置数据源参数,而是在运行时声明它。当您运行您的应用程序时,您可以覆盖 application.properties 中定义的任何属性或定义新的属性。

例如:

java -jar my-spring-boot-app.jar --spring.datasource.url=jdbc:h2:mem:test --spring.datasource.username=sa --spring.datasource.password= secret

更复杂的方法是使用 spring-cloud-config-serverConsul用于管理您的设置。

关于java - 如何在 Spring Boot 中手动配置 JdbcTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971320/

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