Syed
Syed

Reputation: 2607

Can I create a constructor for a @Component class in Spring

This is my component class

@Component
@ConfigurationProperties(prefix = "default-values")
public class DefaultConfig {

    private Map<String, String> countries = new HashMap<>();
    private WHO whoHdr;

    DefaultConfig() {

        countries.put("966 - Saudi Arabia", "966");
        countries.put("965 - Kuwait", "965");        
    }

}

Under my application.yaml file, I've configured values to be set for 'WHO' fields.

But, since I have defined DefaultConfig class as a @Component, can I create a constructor separately for creating a HashMap object? Because I cannot create an instance of DefaultConfig using New keyword if I want to inject this into another class.

Is there any better way to have this countries object instead of putting them in a default constructor which should be ready for Autowiring?

Upvotes: 6

Views: 14355

Answers (2)

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

@PostConstruct

is an annotation for bean component methods which executes before the bean is registered to the context. You can initialize defaults / constants values in this method.

Refer below link for more information:

https://www.journaldev.com/21206/spring-postconstruct-predestroy

Upvotes: 11

Mark Bramnik
Mark Bramnik

Reputation: 42491

First of all:

You don't need to put @Component on classes marked as @ConfigurationProperties apart of the fact that spring can map the configuration data into these classes, they are regular spring beans and therefore can be injected into other classes.

You do need however "map" this configuration properties by @EnableConfigurationProperties(DefaultConfig.class) on one of your Configuration classes (or even @SpringBootApplication which is also a configuration class).

Now Since @ConfigurationProperties annotated class is a spring bean, you can use @PostConstruct on it to initialize the map:

@ConfigurationProperties(prefix = "default-values")
public class DefaultConfig {

    private Map<String, String> countries = new HashMap<>();
    private WHO whoHdr;

    @PostConstruct
    void init() {

        countries.put("966 - Saudi Arabia", "966");
        countries.put("965 - Kuwait", "965");        

    }  

    //setter/getter for WHO property 

}

@Configuration
@EnableConfigurationProperties(DefaultConfig.class)
class SomeConfiguration {

}

Its worth to mention that in Spring boot 2.2 ConfigurationProperties classes can be immutable, so you won't need getter/setter.

Upvotes: 3

Related Questions