Java 在Spring上下文中查找*.properties文件的绝对路径
我有一些遗留罐,我正试图在spring环境中工作 在applicationContext.xml中,我使用以下方式加载属性文件: 我考虑过使用:Java 在Spring上下文中查找*.properties文件的绝对路径,java,spring,maven,tomcat,apache-commons-config,Java,Spring,Maven,Tomcat,Apache Commons Config,我有一些遗留罐,我正试图在spring环境中工作 在applicationContext.xml中,我使用以下方式加载属性文件: 我考虑过使用: String config[] = { "classpath*:META-INF/spring/applicationContext.xml" }; ApplicationContext ctx = new ClassPathXmlApplicationContext(config); 然后使用ctx.getResource劫持路径,
String config[] = { "classpath*:META-INF/spring/applicationContext.xml" };
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
然后使用ctx.getResource劫持路径,但除了第二次加载applicationContext以获取application.properties的绝对路径非常低效之外,它还将导致执行@PostConstruct的无限循环
遗留代码使用Commons配置(据我所知,并基于依赖性错误)来设置其配置,我要寻找的是Commons配置加载正确的application.properties文件的方法,无论它是在Linux、Windows、WAR文件还是嵌入式Tomcat上运行,等等。似乎您的legacyCode需要一个正确的文件路径,并且不理解Spring资源(
“classpath*:META-INF/Spring/applicationContext.xml”
)
我个人会做以下工作:
LegacyCode.init(new File(this.getClass().getClassLoader().getResource("application.properties").toURI()).getPath());
getResource(“application.properties”)
是Spring上下文中Spring符号的Java等价物添加此bean
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer" />
<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer" />
然后注释变量
@值(${cert.path}”)
私有字符串路径 Spring xml中有多个属性文件,但LegacyCode只接受一个?没错,我需要的遗留内容的配置是分段的,所以对于jar1我需要一个特定的配置,而对于jar2我需要一个不同的配置,两者都使用Commons配置,Spring两者都需要,您的答案看起来可以完成任务,稍后将进行测试并返回您的答案。100%有效,这是我最后使用的:LegacyCode.init(新文件(this.getClass().getClassLoader().getResource(“META-INF/spring/application.properties”).toURI().getPath());谢谢你,尤南迪达斯!!
LegacyCode.init(new File(this.getClass().getClassLoader().getResource("application.properties").toURI()).getPath());
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer" />
<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer" />
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:mypropfile.properties")
public class Config {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}