Search code examples
javaspringspring-bootrabbitmqspring-amqp

Looking for a way to parse values in springboot application.yml file before SpringBootApplication is initialized


So my problem is as follows:

I'm using spring AMQP to connect to a rabbitMQ instance that using SSL. Unfortunately, spring AMQP does not currently support full length amqps URIs and adding support is not high on the priority list (see issue: https://github.com/spring-projects/spring-boot/issues/6401 ). They need to be separated.

The following fields are required in my application.yml to connect:

spring:
  rabbitmq:
    host: hostname
    port: portnumber
    username: username
    password: password
    virtual-host: virtualhost
    ssl:
      enabled: true

My VCAP_Services environment for my rabbitMQ instance only provides the virtualhost and the full length uri in the following format: amqps://username:password@hostname:portnumber/virtualhost

Copy and pasting these values into my application.yml is fine for now, but in the long run is not viable. They will need to come from vcap_services.

My @SpringBootApplication has @Beans that initialize a connection to the rabbitMQ instance on startup, so I am looking for a way to parse out the individual values and set them before the application is started.


Solution

  • If you are just interested in reading the properties before your Spring Boot application is initialized, you can parse the yaml file using Spring's YamlPropertiesFactoryBean before you call SpringApplication.run. For example,

    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {       
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(new ClassPathResource("application.yml"));
            Properties props = yamlFactory.getObject();
    
            String hostname = props.getProperty("spring.rabbitmq.hostname");
            ...
    
            SpringApplication.run(Application.class, args);
        }
    }