2017-10-17 7 views
3

を含むファイルがあります。ポート番号、コンテキストルートパス、アプリケーション名のようなプロパティがあります。Springブートのクラスパスにファイルを追加する

そして、私は次のように持っている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クラスからプロパティにアクセスすることができます:私は戦争を構築し、春ブーツ(java -jar server.war)、内部my.properties解決さを実行して、すべてが期待どおりに動作する場合は

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

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

or like `${my.prop}` 

しかし、私はそのファイルを外部の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を上書きします。しかしそれは決して起こらない。クラスパスから余分なファイルを追加した場合

@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; 
} 

値の値または@value注釈を取得するためにEnvironmentオブジェクトを使用する:({「override.propertiesクラスパス」})

+0

この設定では、「springProperties」の修飾子なしでこれを実行しようとしましたか?外部からロードしている 'my.properties'のコピーは、そのコンテキストに影響を与えません。 – dillius

答えて

1

あなたは@PropertySourceを使用することができますあなたはSpringブートを使用しています。以下のコードを使用してApplicationContextを取得することができます。

ConfigurableApplicationContext ctx = app.run(args); 

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

上記の後、私はちょうど実行しなければなりませんでした: 'java -jar server.jar --spring.config.location = my.properties' – yeralin

+0

プロパティファイルもresourcesディレクトリに置くことができます。 Springブートはクラスパスからファイルを取得します。 – Debopam

関連する問題