2016-06-20 8 views
2

私は現在、次のコードを持っている:Springの@Valueをプロパティファイルなしで使用する方法は?

int port = System.getProperty("port") != null ? 
      Integer.parseInt(System.getProperty("port")) : 
      8080; 

を私はこれが好きではないと春の代替と交換したいと思います。だから、@Value注釈を使うべきだと思った。私はこれのためのプロパティファイルを持っているとは思わない。しかし、私は注釈を介してデフォルト値を持っていたいと思います。

プロパティファイルなしでこれを行う方法はありますか、適切なコードの実装は何ですか?まだPropertySourcesPlaceholderConfigurerが必要ですか?これを行う方法の実例を私に見せてください。

+0

春の回答のバージョンは必須ですか? – tkachuko

+0

4.2.3.RELEASE、私は信じています....最新のものの前の最後のもの。 – carlspring

+1

'@ PropertySourcesPalceholderConfigurer'を追加して' @Value( "$ {port:8080}" ''を追加してください)再起動して終了プロパティーファイルを使う必要はありません。 PropertySourcesPlaceholderConfigurer'でもSpELを使用することができますが、これはシステムまたは環境のプロパティのみに制限され、フォールバックが必要な場合は複雑になります。 –

答えて

4

は、設定ベースのJavaを使用していると仮定。

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

その後@Value

@Value("${port:8080}") 
private int port; 

でフィールドに注釈を付けるこれは、指定されたプロパティportのためのシステムプロパティと環境をチェックします。チェックされるJNDIを有効にすると、サーブレットベースの環境ではサーブレット変数として持つことができます。

PropertySourcesPlaceholderConfigurerの使用には、いくつかの異なる実装があるPropertySourceが必要なプロパティファイルは必要ありません。

PropertySourcesPlaceholderConfigurerを登録したくない場合は、SpELに戻すことができますが、それはもう少し複雑になります(そして醜いimho)。

1

私は試していませんが、SpEL expressionを使用できます。私はsafe navigation operatorを使用してい

@Value("#{systemProperties['port'] ?: 8080}") 
private int port; 

注:あなたのコードは以下のように書き換えることができます。

PropertySourcesPalceholderConfigurerについては、私はあなたのクラスパスに春の式言語の依存関係を持っている与えられた、あなたがいずれかが必要とは思わない:

<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-expression</artifactId> 
    <version>4.2.3.RELEASE</version> 
</dependency> 
1

テスト済みです。

  1. はい、あなたはしかし、それはあなたのこのようなシステム変数プロパティファイル
  2. リファレンスを必要としないPropertyPlaceholderConfigurerが必要になります。@Value("#{systemEnvironment['YOUR_VARIABLE_NAME'] ?: 'DEFAULT_VALUE'}"

コードサンプル:

package abc; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 

@Component 
public class Test { 

    public final String javaPath; 

    @Autowired 
    public Test(@Value("#{systemEnvironment['Path']}") String javaPath) { 
     this.javaPath = javaPath; 
    } 
} 

構成:

@Configuration 
@ComponentScan("abc") 
public class Config { 

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

すべてのサンプルの実行:

public class Runner { 

    public static void main(String[] args) { 
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); 
     Test bean = context.getBean(Test.class); 
     System.out.println(bean.javaPath); 
    } 
} 

はそれがお役に立てば幸いです。

関連する問題