Suman
Suman

Reputation: 5

Spring boot - How to Load environment specific properties when class is present in a different package

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;

Upvotes: 0

Views: 402

Answers (1)

mrkernelpanic
mrkernelpanic

Reputation: 4451

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!

Upvotes: 1

Related Questions