Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringBoot difference between @Configuration and @configurationProperties

Tags:

spring-boot

From spring boot documentation, @ConfigurationProperties will

generate your own configuration metadata file from items annotated with @ConfigurationProperties

I tried use @Configuration and @ConfigurationProperties separately on my configuration class.

@Component
//@Configuration
@ConfigurationProperties 
@EnableSpringDataWebSupport
@EnableAsync
public class AppConfig {
    ...
}

I didn't see any noticable difference.

What's the usage of @ConfigurationProperties or @Configuration?

like image 398
LunaticJape Avatar asked Oct 30 '18 20:10

LunaticJape


1 Answers

@Configuration is used to create a class the creates new beans (by annotating its methods with @Bean):

@Configuration
public class CustomConfiguration {

    @Bean
    public SomeClass someClass() {
        return new SomeClass();
    }
}

@ConfigurationProperties binds external configuration into the fields of the class which it annotates. It's common to use it with a @Bean method to create a new bean that encapsulates configuration which can be controlled externally.

Here's a real world example of how we've used it. Consider a simple POJO that holds some values related to connecting to ZooKeeper:

public class ZookeeperProperties
{
    private String connectUrl;

    private int sessionTimeoutMillis = (int) TimeUnit.SECONDS.toMillis(5);

    private int connectTimeoutMillis = (int) TimeUnit.SECONDS.toMillis(15);

    private int retryMillis = (int) TimeUnit.SECONDS.toMillis(5);

    private int maxRetries = Integer.MAX_VALUE;

    // getters and setters for the private fields
}

Now we can create a bean of type ZookeeperProperties and automatically populate it using external configuration:

@Configuration
public class ZooKeeperConfiguration {

    @ConfigurationProperties(prefix = "zookeeper")
    @Bean
    public ZookeeperProperties zookeeperProperties() {

        // Now the object we create below will have its fields populated
        // with any external config that starts with "zookeeper" and
        // whose suffix matches a field name in the class.
        //
        // For example, we can set zookeeper.retryMillis=10000 in our
        // config files, environment, etc. to set the corresponding field
        return new ZookeeperProperties();
    }
}

The benefit of this is that it's less verbose than adding @Value to every field of ZookeeperProperties. Instead, you provide a single annotation on the @Bean method and Spring automatically binds any external configuration it finds with the matching prefix to the fields of that class.

It also lets different users of my class (i.e. anyone who creates a bean type of ZookeeperProperties) use their own prefix to configure the class.

like image 71
Mike Avatar answered Jun 11 '23 06:06

Mike