DamienMiheev DamienMiheev - 3 months ago 55
Java Question

How work with 3rd-party @ConfigurationProperties @Bean?

I use IntellijIdea and gradle. Gradle config:

...
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'
}


Ok, for creating my own properties i need:

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

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


And after i rebuild project spring-boot-configuration-processor genereate new META-INFO, so in application.properties i can use own.prefix.field= and Spring see it.

But what should i do with 3rd party configuration class?
Docs http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html say:


As well as using
@ConfigurationProperties
to annotate a class, you
can also use it on
@Bean
methods. This can be particularly useful
when you want to bind properties to third-party components that are
outside of your control.

To configure a bean from the Environment properties, add
@ConfigurationProperties
to its bean registration:

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


Any property defined with the foo prefix will be mapped onto that
FooComponent bean in a similar manner as the ConnectionProperties
example above.


Ok. Lets try. For example I declare bean like in gide (https://spring.io/guides/tutorials/spring-boot-oauth2/):

@Configuration
@EnableOAuth2Sso
public class SocialConfig {

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

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


But after rebuilding project property facebook.client and facebook.resource do not exist in my application.properties.

Also i tried add SocialConfig.class to

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


After rebuild it still not work.
And like this:

@Configuration
@EnableConfigurationProperties
public class AppConf {}


Still the same.

What am I doing wrong?
Also sorry for my English :)

Answer

What you're doing wrong is that the methods in your @Configuration class are not public. Just add public to facebook and facebookResource and you'll be fine. I've just polished that donc in c4cb8317 and I've submitted a PR to fix the tutorial you were using as a base