Balázs Németh
Balázs Németh

Reputation: 6637

Make @RefreshScope default

If I annotate a bean as @RefreshScope, I can get a new instance of it after its configuration changes (eg. by triggering the refresh by calling /refresh).

But this is exactly I'd like for each of my beans: why would I change a configuration file and then expect the configuration to take effect for some part of the application immediately and for some part only after restart?

So the question is whether it's possible to apply it as a default scope?

Also in a typical Spring Boot application a lot gets auto-configured (eg. datasource), and without a default scope, I'd have to build the beans myself and annotate them properly. (edit: @ConfigurationProperties are automatically refreshed, and since a Spring Boot Datasource auto configuration is based on that, it is refreshed indeed without @RefreshScope)

What am I missing here?

Upvotes: 0

Views: 1652

Answers (2)

Balázs Németh
Balázs Németh

Reputation: 6637

https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_environment_changes and https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_refresh_scope has all the answers.

@ConfigurationProperties are automatically refreshed when /refresh is called, so beans using these properties get the fresh values, for the others and @Value there's @RefreshScope.

I don't think making @RefreshScope default is possible.

Upvotes: 1

Marcos Barbero
Marcos Barbero

Reputation: 1119

The beans annotated with @RefreshScope don't get automatically refreshed after a configuration is changed. It gets refreshed only after the cache entry is invalidated.

From the docs:

Refresh scope beans are lazy proxies that initialize when they are used (i.e., when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you just need to invalidate its cache entry.

One way to invalidate the cache is by using the /refresh endpoint. It's valid to note that a refresh-scoped bean can lead to unexpected behavior, please refer to the docs mentioned above to understand why this is not the default behavior.

Upvotes: 0

Related Questions