gaurav sk
gaurav sk

Reputation: 56

How to avoid putting @RefreshScope on multiple beans in my application

We are externalizing configuration of our microservices (spring boot based) using spring cloud.

As per my understanding on Spring Cloud, to enable the beans loading refreshed/updated values from Config server we need to do 2 things in Spring Cloud Client:

  1. add @RefreshScope on the beans reading values from property files using @Value
  2. add spring actuator to provide /refresh endpoint to refresh the context.

Scenario: We have 100s of classes reading values from property file using @Value. I have to mark all these beans refresh enabled using @RefreshScope annotation.

How can I avoid putting @RefreshScope annotation on all these classes. Is there any shortcut or spring cloud feature to get around this situation.

Upvotes: 2

Views: 4171

Answers (2)

Martin Frey
Martin Frey

Reputation: 10075

You could encapsulate your @Values into one (or several) ConfigurationService bean which is @RefreshScoped and autowire this service into your classes instead. That way you only have a small amount of request scoped beans and your services can stay singletons.

Upvotes: 1

luboskrnac
luboskrnac

Reputation: 24561

You may want to look into Spring Boot feature called @ConfigurationProperties. It is designed to better organize several external configuration options.

According this Github issue, it should work for spring-cloud without @RefreshScope usage.

EDIT (reaction on comment): Maybe you are missing point of @ConfigurationProperties. With this annotation, you wouldn't use it in other configuration classes. You would have dedicated class (or few classes) only for reading and providing properties. Other configuration classes would inject this configuration holder bean.

Upvotes: 1

Related Questions