java - Spring 。发生事件时如何手动连接数据库

标签 java database spring postgresql spring-data-jpa

在我的应用程序中有两种模式:管理员模式和用户模式。仅当启用管理模式时我才需要连接到数据库。为了使用数据库,我使用 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/

相关文章:

java - slf4j 日志记录问题 - 未生成日志文件

java - 哪种做法更好(多次从另一个方法调用方法或自己做同样的事情)

php - 在mysql上使用关系表选择时生成自定义数组

database - Yii:使用模块特定的数据库进行访问控制

java - spring 使用哪个模型类来响应请求映射方法的错误?

java - 从左到右的 Sprite 动画,我应该选择什么?动态的还是运动学的?

python - ZODB python : how to avoid creating a database with only one big entry?

java - Spring中Thymeleaf异常解析文档

java - 在中使用 Autowiring 对象

java - 让 Java Applet 查找嵌入在单个 jar 文件中的 jar 库