Search code examples
javadatabasespring-bootspring-boot-admin

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


I have spring boot admin project and now I hardcoded the username and passwords in application.properties file like this.

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

But want to get that values from database not hardcoded like this.I want to configs to connect to self register the admin server as a client.I am beginner to SpringBoot. How can I do it? Thanks.


Solution

  • So every configuration in an application.properties file can be configured via Javacode. First you have to create a Datasource for your project. Add the spring-data-jpa dependency to your project and config the datasource.

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

    more you can find here: A Guide to JPA with Spring

    To configure for example the two properties spring.boot.admin.client.username=user and spring.boot.admin.client.password=pass you need to create a @Configuration class which creates a 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;
        }
    }
    

    So the JdbcTemplate has already a Database connection and creates the query to get the Username and Password from the Database. The ClientProperties Bean can then be set.

    P.S.: This code is not tested but gives you a some hints to get the job done.