java 如何在Spring中使用@ImportResource注解从类路径加载多个配置文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27266216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:31:11  来源:igfitidea点击:

How to load multiple configuration file from classpath using @ImportResource annotation in Spring

javaspring-mvc

提问by RE350

I don't know,how to load multiple configuration files from classpath in spring using @ImportResource.I have already gone through the link Spring 3 @ImportResource with multiple filesbut no luck so far. My code is below.

我不知道,如何在 spring 中使用@ImportResource从类路径加载多个配置文件。我已经通过链接 Spring 3 @ImportResource 访问了多个文件,但到目前为止还没有运气。我的代码如下。

@Configuration
@PropertySource("classpath:apis.application.properties")
@ComponentScan(basePackages = {"org.surfnet.oaaas.resource", "org.surfnet.oaaas.service"})
@ImportResource({"classpath:spring-repositories.xml,classpath:commonApplicationContext.xml"})
@EnableTransactionManagement
public class SpringConfiguration {

}

Exception i am facing is

我面临的例外是

java.io.FileNotFoundException: class path resource [spring-repositories.xml,classpath:commonApplicationContext.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

How ever when i try to load a single file,like below.it works for both file.But i can not include two ImportResourceannotation in a java class.

当我尝试加载单个文件时,就像下面一样。它适用于两个文件。但是我不能ImportResource在 java 类中包含两个注释。

    @ImportResource("classpath:spring-repositories.xml"})

回答by Jesper

You are using the wrong syntax. Look carefully at how it's done in the question you linked to.

您使用了错误的语法。仔细查看您链接到的问题中它是如何完成的。

There are two strings, not one string containing names separated by commas:

有两个字符串,而不是一个包含以逗号分隔的名称的字符串:

@ImportResource({"classpath:spring-repositories.xml", "classpath:commonApplicationContext.xml"})

回答by Beri

But you were almoust right:) It is simmilar like ComponentScan:

但你几乎是对的:) 它类似于 ComponentScan:

@ImportResource({"classpath:spring-repositories.xml","classpath:commonApplicationContext.xml"})

When you define resources inside {}, than you put each resource as separate String, optionally with file:, classpath: prefix.

当您在 {} 中定义资源时,您将每个资源作为单独的字符串放置,可选择使用 file:, classpath: 前缀。

I have found also this stack page:

我还发现了这个堆栈页面:

Spring 3 @ImportResource with multiple files

带有多个文件的 Spring 3 @ImportResource