@PropertySource属性路径未解析

时间:2016-02-11 05:17:46

标签: java spring properties configuration annotations

我已经设置了环境变量JAVA_OPTS(-Dappconfig = D:/ cc / dd -Dfarm = test并希望使用以下代码从属性中读取属性,但无论我尝试了什么,我都得到了以下错误。我需要为不同的环境(测试,登台,开发,生产)做这个。感谢任何帮助

        Caused by:
            java.lang.IllegalArgumentException: Could not resolve placeholder 'appconfig' in string value
 "file:${appconfig}/farm/${farm}/myservice.appconfig.properties"


@Configuration
@PropertySource(value = "file:${appconfig}/farm/${farm}/myservice.appconfig.properties", ignoreResourceNotFound = false)
public class AppConfig
{
    @Autowired
    private Environment environment;


    @Bean
    public AppConfigSettings getAppConfig()
    {
        AppConfigSettings properties = new AppConfigSettings()

         //I set properties using environment.getRequiredProperty("propertykey") //here


        return properties;
    }

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

2 个答案:

答案 0 :(得分:0)

赞赏此answer

我将环境变量设置为

_JAVA_OPTIONS = -Dfarm = test -Dappconfig = D:\ cc \ dd

使用_JAVA_OPTIONS而不是JAVA_OPTS

现在完美无缺

答案 1 :(得分:-1)

documentation for the PropertySource annotation的一部分可以说明@PropertySource资源位置内的占位符:

  

@PropertySource资源位置中存在的任何$ {...}占位符将根据已针对环境注册的属性源集合进行解析。例如:

@Configuration
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")
public class AppConfig {
    @Autowired
    Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}
  

假设“my.placeholder”存在于已注册的其中一个属性源中,例如系统属性或环境变量,占位符将被解析为相应的值。如果没有,则“default / path”将用作默认值。表示默认值(由冒号“:”分隔)是可选的。如果未指定缺省值且无法解析属性,则将抛出IllegalArgumentException。

我不确定您可能正在使用的其他@PropertySource注释,或者您是否甚至可以控制它们的应用顺序,但这似乎可能是您遇到的情况。

相关问题