Search code examples
javaspringconditional-statementsapplicationcontext

Conditionally load application context


How can I load a spring-beans xml file from one out of two locations?

  • System.getProperty("conf.dir") + "/context.xml" if it exist, otherwise fall back to
  • classpath:/context.xml

This is what I started out with but I only want to load the first found context

@Configuration
@ImportResource({"${conf.dir}/context.xml", "classpath:/context.xml"})
public class AppConfig {
     @Autowire somethingFromAboveXmlContext;
}

I've looked into @Conditional but the solution becomes a bit non-intuitive.

@Configuration
@Conditional(AppContextCondition.class)
@ImportResource("${conf.dir}/context.xml")
@ImportResource("classpath:/context.xml")
public class AppConfig {
     @Autowire somethingFromAboveXmlContext;
}

Is there a manual approach to do what ImportResource does?


Solution

  • You can try this:

    @Configuration
    @ImportResource({"${conf.dir}/context.xml"})
    public class AppConfig {
     static {
        if(!System.getProperties().contains("conf.dir")) {
            System.setProperty("conf.dir", "classpath:");
        }
     }
     @Autowire somethingFromAboveXmlContext;
    }
    

    I agree that it might not be a perfect solution, but it could work!