gpt4 book ai didi

spring - 如何在运行时在spring中加载额外的bean配置文件

转载 作者:行者123 更新时间:2023-12-04 17:18:37 25 4
gpt4 key购买 nike

我有一个spring app, future 我们会开发更多的类,对于这些类我们还会使用额外的配置文件(不覆盖现有的)来定义bean。那么如何动态加载它们呢?我知道有一个ApplicationContextAware接口(interface),我可以运行一个bean来检查是否有新的配置文件可用,如果它们来了,我可以运行

setApplicationContext(ApplicationContext applicationContext)

但是那么如何使用 ApplicationContext 来加载附加的配置文件呢?

更新:
如果应用程序是从 XML 加载的,那么我可以将 ApplicationContext 转换为 ClassPathXmlApplicationContext 然后使用加载方法,但是如果 AnnotationConfigApplicationContext,它只有扫描方法来扫描包,但是如果我想从 xml 加载呢?

更新:
以下是我要使用的代码,它使用spring集成来监控折叠,在运行时我可以将jar文件放在类路径中,然后将xml配置放在那个文件夹中,这将触发loadAdditionBeans函数运行,并且会传入xml文件对象,需要做的是将该文件中的上下文添加到当前上下文中而不是创建子上下文。
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);
}

看看上面的代码,如果它有助于解决您的问题,请告诉我。

关于spring - 如何在运行时在spring中加载额外的bean配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27580811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com