Spring Framework
This example shows that the configuration imported by DeferredImportSelector overrides the main configuration
package com.logicbig.example;import org.springframework.context.annotation.DeferredImportSelector;import org.springframework.core.type.AnnotationMetadata;public class MyImportSelector implements DeferredImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { String prop = System.getProperty("myProp"); if ("someValue".equals(prop)) { return new String[]{MyConfig1.class.getName()}; } else { return new String[]{MyConfig2.class.getName()}; } }}
package com.logicbig.example;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyConfig1 { @Bean AppBean appBean() { return new AppBean("from config 1"); }}
package com.logicbig.example;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyConfig2 { @Bean AppBean appBean() { return new AppBean("from config 2"); }}
package com.logicbig.example;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;@Configuration@Import(MyImportSelector.class)public class MainConfig { @Bean ClientBean clientBean() { return new ClientBean(); } @Bean AppBean appBean() { return new AppBean("from main config"); }}
package com.logicbig.example;public class AppBean { private String message; public AppBean(String message) { this.message = message; } public String getMessage() { return message; }}
package com.logicbig.example;import org.springframework.beans.factory.annotation.Autowired;public class ClientBean { @Autowired private AppBean appBean; public void doSomething() { System.out.println(appBean.getMessage()); }}
package com.logicbig.example;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class DeferredImportSelectorExample { public static void main(String[] args) { System.setProperty("myProp", "someValue"); ApplicationContext context = new AnnotationConfigApplicationContext( MainConfig.class); ClientBean bean = context.getBean(ClientBean.class); bean.doSomething(); }}
from config 1