如何从数据库中获取 spring.boot.admin.client.username/ password 的值?

how to get values to spring.boot.admin.client.username/ password from database?

我有 spring 引导管理项目,现在我将用户名和密码硬编码在 application.properties 文件中,如下所示。

spring.boot.admin.client.username=user
spring.boot.admin.client.password=pass

spring.boot.admin.client.instance.metadata.user.name=user
spring.boot.admin.client.instance.metadata.user.password=pass

但是想要从数据库中获取这些值而不是像 this.I 那样硬编码想要配置以连接到自我注册管理服务器作为 client.I 我是 SpringBoot 的初学者。我该怎么做?谢谢

因此 application.properties 文件中的每个配置都可以通过 Javacode 进行配置。首先,您必须为您的项目创建一个 Datasource。将 spring-data-jpa 依赖项添加到您的项目并配置数据源。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

您可以在这里找到更多内容:A Guide to JPA with Spring

要配置例如 spring.boot.admin.client.username=userspring.boot.admin.client.password=pass 这两个属性,您需要创建一个 @Configuration class,它会创建一个 ClientProperties Bean。

@Configuration
public class AdminClientConfig {

    private final JdbcTemplate jdbcTemplate;
    private final Environment environment;

    public AdminClientConfig(JdbcTemplate jdbcTemplate,
        Environment environment) {
        super();
        this.jdbcTemplate = jdbcTemplate;
        this.environment = environment;
    }

    @Bean
    public ClientProperties clientProperties() {
        ClientProperties cp = new ClientProperties(environment);

        cp.setUsername(getUsername());
        cp.setPassword(getPassword());

        return cp;
    }

    private String getUsername() {
        String username = jdbcTemplate.queryForObject(
            "select username from AnyTable where id = ?",
            new Object[] { "123" }, String.class);
        return username;
    }

    private String getPassword() {
        String password = jdbcTemplate.queryForObject(
            "select password from AnyTable where id = ?",
            new Object[] { "123" }, String.class);
        return password;
    }
}

因此 JdbcTemplate 已经有数据库连接并创建查询以从数据库中获取用户名和密码。然后可以设置 ClientProperties Bean。

P.S.: 此代码未经测试,但会为您提供一些完成工作的提示。