Spring无法解决占位符问题

如果这是一个愚蠢的问题,我很高兴spring,请原谅我。 当我尝试启动程序时,我收到以下错误: java.lang.IllegalArgumentException: Could not resolve placeholder 'appclient' in string value [${appclient}] 。 执行以下代码时抛出错误:

 package ca.virology.lib2.common.config.spring.properties; import ca.virology.lib2.config.spring.PropertiesConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; @Configuration @Import({PropertiesConfig.class}) @PropertySource("${appclient}") public class AppClientProperties { private static final Logger log = LoggerFactory.getLogger(AppClientProperties.class); { //this initializer block will execute when an instance of this class is created by Spring log.info("Loading AppClientProperties"); } @Value("${appclient.port:}") private int appClientPort; @Value("${appclient.host:}") private String appClientHost; public int getAppClientPort() { return appClientPort; } public String getAppClientHost() { return appClientHost; } } 

资源文件夹中存在一个名为appclient.properties的属性文件,其中包含主机和端口的信息。 我不确定"${appclient}"的定义在哪里,如果有的话。 也许它甚至没有定义,这导致了问题。 我是否需要将"${appclient}"更改为"${appclient}" "{classpath:/appclient.properties}"或者我错过了其他内容?

您没有正确读取属性文件。 propertySource应该将参数传递为: file:appclient.propertiesclasspath:appclient.properties 。 将注释更改为:

 @PropertySource(value={"classpath:appclient.properties"}) 

但是我不知道你的PropertiesConfig文件包含什么,因为你也导入了它。 理想情况下,应该保留@PropertySource注释。

如果您使用的是Spring 3.1及更高版本,则可以使用类似……

 @Configuration @PropertySource("classpath:foo.properties") public class PropertiesWithJavaConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } 

你也可以像xml配置一样…

     

在早期版本中。

对于需要在WAR之外管理的属性:

  

例如,如果application.yml内部是nameid

然后你可以在xml spring中的运行时创建bean