0

I want to load enviroment specific properties base on profile. However, my main boot app is residing in a different package.

-project structure

-proj-test

 -src/main/java -com.x - AppBoot.java (Spring boot main app) -com.x.service - Subscriber.java -src/main/resources -application-dev.properties -application-test.properties application-dev.properties mq.hostname=spring profile dev application-test.properties mq.hostname=spring profile test 

AppBoot.java

package com.x @SpringBootApplication(scanBasePackages = { "com.x" }) public class AppBoot { @Autowired private Subscriber subscriber; @Value("${mq.hostname}") private String hostName; public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(AppBoot.class, args); log.debug("hostName... in Main.java " + hostName); } } package com.x.service @Component public class Subscriber { @Value("${mq.hostname}") private String hostName; public Subscriber() { log.debug("hostName... in Subscriber .java " + hostName); } } 

Problem - log.debug("hostName... in Main.java " + hostName); in AppBoot.java is getting printed with property value; however , log.debug("hostName... in Subscriber .java " + hostName) in Subscriber.java is coming as null;

1
  • At runtime, you can provide @Profile values for loading your application-<profile_name> files, Spring will automatically inject property will based on profile Commented Oct 24, 2017 at 9:04

1 Answer 1

1

The Problem is, that Spring will inject your property AFTER the Bean 'Subscriber' is created!

So put your log.debug("hostName... in Subscriber .java " + hostName); in a different location and not in the constructor!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Added a method instead of constructor and it's working. Cheers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.