2017-06-24 8 views
2

はそのようなゲッターとセッターを持つクラスを作成しなければならない@ConfigurationProperties注釈いずれかを使用します。@ConfigurationPropertiesクラスを変更から保護する方法は?

@ConfigurationProperties(prefix = "some") 
public class PropertiesConfig { 
    private boolean debug; 

    public boolean isDebug() { 
     return debug; 
    } 

    public void setDebug(boolean debug) { 
     this.debug = debug; 
    } 
} 

をしかし、これは呼び出すことで、誰かがこの値を変更するように誘惑される状況につながる:

@Autowire 
private PropertiesConfig config;   
//.... 

config.setDebug(true); 

はですsetterと外部パーサ/リーダークラスを持たない@ConfigurationProperties注釈付きクラスを作成する方法はありますか?

答えて

0

すぐに使用することはできません。 @ConfigurationProperties豆には標準的なゲッターとセッターが必要です。 Immutable @ConfigurationProperties

またはこのような何か:あなたはこの回答に記載されているアプローチを検討する必要がありますできるだけ定型コードと

@Component 
public class ApplicationProperties { 

    private final String property1; 
    private final String property2; 

    public ApplicationProperties(
    @Value("${some.property1"}) String property1, 
    @Value("${some.other.property2}) String property2) { 
    this.property1 = property1; 
    this.property2 = property1; 
    } 

    // 
    // ... getters only ... 
    // 

} 
0

一つのアプローチは、ゲッターのみ

public interface AppProps { 
    String getNeededProperty(); 
} 
とのインターフェースを使用しているだろう

と、Lombokの@Getter@Setterアノテーションの助けを借りて実装の定型文ゲッターとセッターを取り除く:

@ConfigurationProperties(prefix = "props") 
@Getter 
@Setter 
public class AppPropsImpl implements AppProps { 
    private String neededProperty; 
} 

そして、豆BOのみインターフェイスによって他のBeanにアクセスできる、一つは、代わり@Componentとしてマーキングまたはメインアプリケーションクラスに@EnableConfigurationProperties(AppPropsImpl.class)を使用する、ことによってそれを公開する構成にそれを置くことを検討することができインターフェース:

@Configuration 
@EnableConfigurationProperties 
public class PropsConfiguration { 
    @Bean 
    public AppProps appProps(){ 
     return new AppPropsImpl(); 
    } 
} 

は今、このBeanが唯一のインターフェイスを使用して注入することができ、これは他のBeanにセッターを使用できない可能:

春ブーイングでテスト
public class ApplicationLogicBean { 
    @Autowired 
    AppProps props; 

    public void method(){ 
     log.info("Got " + props.getNeededProperty()); 
    } 
} 

t 1.5.3およびロンボク1.16.16。

関連する問題