2017-10-17 71 views
3

我有server.yml文件,其中包含僅限於Spring Framework屬性,如端口號,上下文根路徑,應用程序名稱。將文件添加到Spring Boot的類路徑

而且,我有一個applicationContext.xml有以下幾點:

<util:properties id="springProperties" location="classpath*:my.properties"> 
<context:property-placeholder location="classpath*:my.properties" 
     local-override="true" properties-ref="springProperties" /> 

my.properties文件駐留在src/main/resources目錄項目。

那麼,我可以從我的Java類,如訪問屬性:

@Autowired 
@Qualifier("springProperties") 
private Properties props; 

public String getProperty(String key){ 
    return props.getProperty(key); 
} 

or like `${my.prop}` 

當我建立戰爭和運行春季啓動(java -jar server.war),內部my.properties議決,一切都按預期工作。

但是,我想覆蓋該文件與外部my.properties。 我讀https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

我試圖運行是這樣的:

java -jar server.jar --spring.config.location=classpath:/my.properties

java -jar server.jar --spring.config.location=my.properties

但我可以通過這個覆蓋的屬性只有從我server.yml。意思是說,我可以覆蓋端口號或應用程序名稱。但內部my.properties從不受影響。

我做錯了什麼?我明白,外部my.property只是應該在類路徑中,然後它覆蓋內部my.property。但它從未發生過。

+0

您是否嘗試過在沒有此配置的'springProperties'限定符的情況下執行此操作?您在外部加載的'my.properties'副本可能不會影響該上下文。 – dillius

回答

1

您可以使用@PropertySource({「類路徑:override.properties」})從classpath中添加額外的文件,然後使用環境對象來獲取值或@Value註解值

@PropertySource({ "classpath:other.properties" }) 
@Configuration 
public class Config{ 
    @Autowired 
    private Environment env; //use env.getProperty("my.prop") 

    @Value("${my.prop}") 
    private String allowedpatterns; 
} 

@Component 
public OthenClass{ 

    @Autowired 
    //If this class is not component or Spring annotated class then get it from ApplicationContext 
    private Environment env; //use env.getProperty("my.prop") 

    @Value("${my.prop}") 
    private String allowedpatterns; 
} 

如果您正在使用下面的代碼可以使用Spring Boot獲得ApplicationContext

ConfigurableApplicationContext ctx = app.run(args); 

Environment env = ctx.getBean(Environment.class); 
+0

之後,我不得不運行: 'java -jar server.jar --spring.config.location = my.properties' – yeralin

+0

您也可以將屬性文件放在資源目錄中。 Spring引導將從類路徑中選取文件。 – Debopam