弹簧无法解析占位符

2022-09-01 08:55:46

我对春天相当陌生,所以如果这是一个愚蠢的问题,请原谅我。当我尝试启动程序时,我收到以下错误:。执行以下代码时,将引发该错误: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}""{classpath:/appclient.properties}"


答案 1

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

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

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


答案 2

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

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

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
}
}

您也可以通过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>

在早期版本中。


推荐