今日も同じ問題に遭遇しましたが、残念ながらAndyの解決策はうまくいきませんでした。Spring Boot 1.2.1.RELEASEではさらに簡単ですが、いくつかの点に注意する必要があります。
これが私の興味深い部分application.yml
です:
oauth:
providers:
google:
api: org.scribe.builder.api.Google2Api
key: api_key
secret: api_secret
callback: http://callback.your.host/oauth/google
providers
マップにはマップエントリが1つだけ含まれています。私の目標は、他のOAuthプロバイダーに動的構成を提供することです。このマップを、このyamlファイルで提供される構成に基づいてサービスを初期化するサービスに挿入したいと思います。私の最初の実装は:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
private Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
アプリケーションの起動後、providers
マップインOAuth2ProvidersService
が初期化されませんでした。アンディが提案した解決策を試しましたが、うまくいきませんでした。私はそのアプリケーションでGroovyを使用しているので、削除private
してGroovyにゲッターとセッターを生成させることにしました。だから私のコードは次のようになりました:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
その小さな変更の後、すべてが機能しました。
言及する価値があるかもしれないことが1つありますが。それを機能させた後、私はこのフィールドを作成private
し、セッターメソッドにストレート引数タイプをセッターに提供することを決定しました。残念ながらそれはうまくいきません。これは、原因となるorg.springframework.beans.NotWritablePropertyException
メッセージで:
Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Cannot access indexed value in property referenced in indexed property path 'providers[google]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Bean property 'providers[google]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Spring BootアプリケーションでGroovyを使用している場合は注意してください。
info
マップを配置できませんMapBindingSample
(おそらく、SpringApplication.run
呼び出し中のアプリの実行に使用されているためです)。