在我的应用程序中有两种模式:管理员模式和用户模式。仅当启用管理模式时我才需要连接到数据库。为了使用数据库,我使用 Spring Data JPA,我选择 postgre 作为数据库。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
这是我的 application.properties
## PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/metrics
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
如果发生事件或条件有效(例如下面的代码),Spring 是否有某种机会手动连接到数据库?
public void start(String[] args) {
if (args[0].equals("user")) {
switch (args[1]) {
//some action
}
}
if (args[0].equals("admin")) {
//some action
//how to connect to db here?
}
}
最佳答案
Spring 有特定的应用程序事件处理,请参阅 引用资料 this article
public class JdbcEvent extends ApplicationEvent...
监听器的伪代码:
public class JdbcEventListener implements ApplicationListener<JdbcEvent> {
@Autowired
DataSourceProperties dataSourceProperties
@Override
public void onApplicationEvent(CustomSpringEvent event) {
if (!jdbcConnectionExists) {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.username(dataSourceProperties.getUsername());
...
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceBuilder.build());
}
}
}
已更新
关于java - Spring 。发生事件时如何手动连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442146/