Accessing shared configuration object using Spring

338 views Asked by At

I am new to Spring and not sure if there is a simple approach to what I am trying to do. Before I migrated some existing code base to Spring, I was manually loading configuration properties in a singleton class called ConfigurationProvider - pretty straight forward.

Now that I have migrated to Spring Cloud Config, I am trying to determine a pragmatic approach to a global configuration object with little to no manual setup. My current implementation is a not-so-singleton class that almost accomplishes what I am looking to do but comes with a design flaw.

@Configuration
public class ConfigurationProvider {

    private static ConfigurationProvider _instance;

    @Autowired
    private StorageConfiguration storage;

    // this being the design flaw
    public ConfigurationProvider() {
        _instance = this;
    }

    public static ConfigurationProvider getInstance() {
        return _instance;
    }

    ...
}

I considered throwing an exception if ConfigurationProvider::_instance is already initialized but this is just tacking onto the existing code smell. With all the bells and whistles of Spring Boot, I'd imagine there is a cleaner approach using one of the hundreds of annotations that is strapped with this framework.

2

There are 2 answers

3
Martin On

you don't need the constructor or the static methods & property. Spring boot takes care of managing the object for you.

Wherever you want to use the ConfigurationProvider declare:

@Autowired
ConfigurationProvider configuration;

and use this instance

0
user0000001 On

Martin's answer is preferable to the solution I was looking for. However, there is a way to inject your beans programmatically but it treads along the lines of an anti-pattern. In my case, I cannot refactor the configuration singleton due to design limitations.

@Autowired
private AutowireCapableBeanFactory autowireFactory;

...

autowireFactory.autowireBean(SingletonClass.getInstance());