Spring无法解析占位符

Brk*_*rkk 23 java 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;
}
}
Run Code Online (Sandbox Code Playgroud)

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

Roh*_*ain 18

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

@PropertySource(value={"classpath:appclient.properties"})
Run Code Online (Sandbox Code Playgroud)

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


小智 11

如果您使用的是Spring 3.1及以上版本,则可以使用类似......

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
}
}
Run Code Online (Sandbox Code Playgroud)

你也可以像xml配置一样...

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">

  <context:property-placeholder location="classpath:foo.properties" />

  </beans>
Run Code Online (Sandbox Code Playgroud)

在早期版本中.


小智 6

希望它仍然有用,application.properties(或application.yml)文件必须在两个路径中:

  • 源代码/主/资源/配置
  • 源代码/测试/资源/配置

包含您所指的相同属性

  • 它有效,但有人可以解释其背后的基本逻辑吗? (2认同)