Dhaval Goti
Dhaval Goti

Reputation: 457

Get property value on Startup of application in Spring boot application

I want to get value of one property from application.properties in my spring boot application. Please see below code.

@Component
public class ContactEntityComp implements InitializingBean, CommandLineRunner
{
    @Value("${amqp.routes.get}")
    public String routes_get;

    @PostConstruct
    public void getCountryList() {
            System.out.println( " routes_get in  PostConstruct- "+routes_get);

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println( " routes_get in  afterPropertiesSet- "+routes_get);

    }

        @Override
    public void run(String... args) throws Exception {
        System.out.println( " routes_get in  afterPropertiesSet- "+routes_get);

    }
}

I want to get value of property - amqp.routes.get from application.properties while spring boot application startup. I have tried with 1) @postConstruct annotation, 2) InitializingBean Interface, 3) CommandLineRunner Interface but I am getting null value of property from application.properties. Is there any other way for this?

Upvotes: 1

Views: 1958

Answers (1)

Matt
Matt

Reputation: 451

You should be able to access it like this.

@Configuration
@PropertySource("classpath:application.properties")
public class SomeConfigClass {
  @Autowired
  private Environment env;

  @Bean
  public Whatever someBeanFunc() {
    String desiredProp = env.getProperty("amqp.routes.get");
  }
}

This is especially useful if you are trying to access a lot of properties in one class.

Upvotes: 1

Related Questions