我今天遇到了同样的问题,但不幸的是,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 map 只包含一个 map 条目,我的目标是为其他 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() {
//....
}
}
启动应用程序后,OAuth2ProvidersService 中的providers 映射未初始化。我尝试了安迪建议的解决方案,但效果不佳。我在那个应用程序中使用 Groovy,所以我决定删除 private 并让 Groovy 生成 getter 和 setter。所以我的代码看起来像这样:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
在那次小改动之后,一切正常。
虽然有一件事可能值得一提。在我让它工作之后,我决定创建这个字段 private 并在 setter 方法中为 setter 提供直接参数类型。不幸的是,它不会起作用。它会导致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,请记住这一点。