如何使用第三方@ConfigurationProperties @Bean?

时间:2016-08-27 23:23:53

标签: java spring spring-boot configuration property-files

我使用IntellijIdea和gradle。 Gradle配置:

...
apply plugin: 'propdeps'
apply plugin: 'propdeps-idea'
apply plugin: 'propdeps-maven'
buildscript {
    repositories {
        maven { url 'http://repo.spring.io/plugins-release' }
    }
    dependencies {
        classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7'
    }
}

compileJava.dependsOn(processResources)
dependencies {
    ...
    optional group: 'org.springframework.boot', name: 'spring-boot-configuration-processor', version: '1.4.0.RELEASE'
}

好的,我需要创建自己的属性:

@Component
@ConfigurationProperties("own.prefix")
@Data
public class TestProps {
    public String field;
}

@Configuration
@EnableConfigurationProperties(TestProps.class)
public class AppConf {}

在我重建项目后,spring-boot-configuration-processor创建了新的META-INFO,所以在application.properties中我可以使用own.prefix.field =和Spring看到它。

但是我该如何处理第三方配置类? 文档http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html说:

  

除了使用@ConfigurationProperties注释一个类之外,还有   也可以在@Bean方法上使用它。这可能特别有用   当您想要将属性绑定到第三方组件时   在你的控制之外。

     

要从Environment属性配置bean,请添加   @ConfigurationProperties到bean注册:

@ConfigurationProperties(prefix = "foo")
@Bean
public FooComponent fooComponent() {
    ...
}
     

使用foo前缀定义的任何属性都将映射到该属性   FooComponent bean的方式与ConnectionProperties类似   上面的例子。

确定。我们试试吧。例如,我在gide(https://spring.io/guides/tutorials/spring-boot-oauth2/)中声明bean:

@Configuration
@EnableOAuth2Sso
public class SocialConfig {

    @Bean
    @ConfigurationProperties("facebook.client")
    OAuth2ProtectedResourceDetails facebook() {
        return new AuthorizationCodeResourceDetails();
    }

    @Bean
    @ConfigurationProperties("facebook.resource")
    ResourceServerProperties facebookResource() {
        return new ResourceServerProperties();
    }
}

但重建项目属性后,我的application.properties中不存在facebook.client和facebook.resource。

我也尝试将SocialConfig.class添加到

@Configuration
@EnableConfigurationProperties(SocialConfig.class)
public class AppConf {}

重建后仍无效。 像这样:

@Configuration
@EnableConfigurationProperties
public class AppConf {}

还是一样。

我做错了什么? 也很抱歉我的英语:)

1 个答案:

答案 0 :(得分:2)

你所犯的错误是@Configuration课程中的方法不公开。只需将public添加到facebookfacebookResource,您就可以了。我刚刚在c4cb8317中完善了该文档,而我用submitted a PR to fix the tutorial作为基础。

由于嵌套对象未使用@NestedConfigurationProperty标记,因此生成的元数据大部分都是空的。我已提交another pull request来修复此问题。

相关问题