2017-04-04 111 views
2

有没有可能从java配置文件加载弹性配置文件?从java配置文件加载额外的弹簧配置文件

我知道我可以使用-Dspring.profile.active参数并在application.properties中将配置文件添加到spring.profiles.include

我需要的是能够从java配置文件激活配置文件。我创建了PropertyPlaceholderConfigurer,我在其中添加了一些自定义属性文件,其中还包含属性spring.profiles.include,所有属性均已加载并且工作正常,但spring不会使用此属性激活任何包含属性的配置文件。

@Bean 
public static PropertyPlaceholderConfigurer ppc() throws IOException { 
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); 
    ppc.setLocations(new ClassPathResource("properties/" + property + ".properties")); 
    ppc.setIgnoreUnresolvablePlaceholders(true); 
    return ppc; 
} 

回答

1

活性弹簧剖面,在通过下列配置属性来定义:spring.profiles.active:

您应该列出所有通过上述配置键导入他们激活的配置文件的文件。

EDIT

首先,作为每official documentation配置spring.profiles.include更适合无条件加入活性谱。

其次,我可以假设PropertyPlaceholderConfigurer不适合你想要达到的目的。官方文件列出了您可以使用的方式Externalize Configuration。你可以尝试使用@PropertySource

@PropertySources({ 
     @PropertySource(value = "classpath:application.properties"), 
     @PropertySource(value = "classpath:other.properties", ignoreResourceNotFound = true) 
}) 
public class Application { 
     ... 
    } 
} 

此外,您可以尝试描述here列出内部application.properties财产spring.config.location其他属性的文件。

+0

我试过'spring.profiles.active'和'spring.profiles.include'。当它包含默认的application.properties或配置文件特有的属性文件时,它会自动工作,但是如果我使用PropertyPlaceholderConfigurer加载它,它会看到此属性,但它不会激活它的任何配置文件。 –

+0

你是绝对正确的。使用'spring.profiles.include'比重写'spring.profiles.active'更适合您的需求。我认为问题是添加一个“PropertyPlaceholderConfigurer”类型的新bean并不是正确的方法。我会编辑我的答案。 –