我有一个spring应用程序,将来我们将开发更多的类,对于这些类,我们还将使用其他配置文件(而不是覆盖现有文件)来定义bean。那么如何动态加载它们呢?我知道有一个ApplicationContextAware接口,我可以运行一个Bean来检查是否有新的配置文件,如果有,我可以运行
setApplicationContext(ApplicationContext applicationContext)
但是,然后如何使用ApplicationContext加载其他配置文件?
更新:如果应用程序是从XML加载的,那么我可以将ApplicationContext转换为ClassPathXmlApplicationContext,然后使用load方法,但是如果AnnotationConfigApplicationContext它仅具有扫描程序包的扫描方法,但是如果我想从xml加载怎么办?
更新:以下是我要使用的代码,它使用spring集成来监视折叠,在运行时我可以将jar文件放在类路径中,然后将xml配置放在该文件夹中,这将触发loadAdditionBeans函数要运行,并将传递xml File对象,需要做的是将该File中的上下文添加到当前上下文中,但不创建子上下文。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
import java.io.File;
@MessageEndpoint
public class FolderWatcher implements ApplicationContextAware {
//private ApplicationContext ctx;
private AnnotationConfigApplicationContext ctx; // it's a spring boot,so the ctx is AnnotationConfigApplicationContext
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx=(AnnotationConfigApplicationContext)applicationContext;
}
@ServiceActivator
public void loadAdditionBeans(File file){
/*
file is an xml configuration file, how to load the beans defined it into the currect context,
I don't what to have another hierarchy, since that will make the beans defined in the file not
available in parent.
*/
}
}
PathMatchingResourcePatternResolver pmrl = new PathMatchingResourcePatternResolver(context.getClassLoader());
Resource[] resources = pmrl.getResources(
"classpath*:com/mycompany/**/applicationContext.xml"
);
for (Resource r : resources) {
GenericApplicationContext createdContext = new GenericApplicationContext(context);
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(createdContext);
int i = reader.loadBeanDefinitions(r);
}
请看上面的代码,让我知道它是否有助于解决您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句