I need to load bean definitions from XML. The file is in a remote location (http) which is configured by properties. The properties should also be loaded from a remote location (a spring cloud config server)
constraints:
- Spring 4.3.14 (not boot)
- should be in runtime and after my properties already loaded
- beans defined in xml are referencing properties in context
- server URI (to fetch the xml from) should be in properties and not environment variable or profile depandant
The current setup I have works well when MY_XML_URI
is passed as environment variable:
${SPRING_CONFIG_URI}/master/application-${spring.profiles.active}.properties
<import resource="${MY_XML_URI}/myBeans.xml"/>
And in the remote location, myBeans.xml with lots of beans e.g.
<bean name="mySpecialBean" class="com.example.MyGenericBean">
<constructor-arg value="mySpecialBean"/>
<constructor-arg value="${special.bean.config.expression}"/>
</bean>
However trouble starts when I want to get MY_XML_URI
from the properties context, it doesn't resolve
…
I have tried several approaches e.g:
java configuration class with
@ImportResource({"${xml.server.uri}"})
but the properties are not loaded yet so it not converting to real value ofxml.server.uri
.@Configuration @ImportResource({"${xml.server.uri:http://localhost:8888}/myBeans.xml"}) public class MyConfiguration {}
expose dummy bean which fetch xml as resource and load the beans to parent applicationcontext - i must have it available to other beans dependant on those beans defined in xml. This solution was not injecting the properties context to my beans so failed to init them.
@Configuration public class RiskConfig { @Value("${xml.server.uri}") private String xmlUri; @Autowired @Bean public Object myBean(ApplicationContext applicationContext) { Resource resource = applicationContext.getResource(xmlUri + "myBeans.xml"); // not working since its not loading the beans to the main context // GenericApplicationContext genericApplicationContext = new GenericApplicationContext(applicationContext); // XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(genericApplicationContext); // reader.loadBeanDefinitions(resource); AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory(); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory; XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); reader.loadBeanDefinitions(resource); return new Object(); } }
Finally - is there a way to load the beans from xml programmatically to parent application context (which is already exist) though they are injected with properties.