0

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.

user0000001
  • 2,092
  • 2
  • 20
  • 48

2 Answers2

2

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

Martin
  • 184
  • 10
  • This would require me to scan the entire package, correct? – user0000001 Jul 01 '19 at 17:28
  • I don't really understand that question. No you don't have to scan the pacakge, the framework - spring - does the scanning for you. That is how enterprise beans and dependency injection work in Spinrg – Martin Jul 02 '19 at 10:08
  • Yes, I get that. It is a very large project and I was trying to keep startup performance in mind. My existing Spring implementation explicitly defines the location of my configuration to avoid this. But I have found a compile-time solution by Spring that will help with this. – user0000001 Jul 02 '19 at 14:49
0

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());
user0000001
  • 2,092
  • 2
  • 20
  • 48