I am writing a class that implements the following method:
public void run(javax.sql.DataSource dataSource);
Within this method, I wish to
There's a more elegant way in which you can use an external xml file and load it with file system resource then inject beans configured in it into your application context. Thus:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
@Service
@Order(-100)
public class XmlBeanInitializationService implements ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
@Value("${xmlConfigFileLocation}")
private String xmlConfigFileLocation;
@Override
public void afterPropertiesSet() throws Exception {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry)applicationContext);
reader.loadBeanDefinitions(new FileSystemResource(xmlConfigFileLocation));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
where ${xmlConfigFileLocation} is a property specified in your application.properties file which points to the file location in your system thus:
xmlConfigFileLocation="your-file-path-anywhere-in-your-system"
and your xml file may contain:
thus when your application starts spring loads the class and loads the bean into application context.
Hope this helps someone.