javaspring-bootconstructor-injection

Order of constructor calls in Spring boot


I have a class ServiceClass annotated with @Service, inside that I do constructor injection for an object.

@Service
public class ServiceClass
{
    Dog dog;

    @Autowired
    public ServiceClass(Dog dog) {
        this.dog = dog;
    }
}

Now I also need to add some configuration code, that should run just once and prior to any other method call inside ServiceClass.

I thought of creating a no arg constructor and put those configuration inside those, but spring doesn't call that constructor.

Should I put it inside constructor where I do injection, or is there some other way to achieve it.


Solution

  • There are in this case two suitable options to go for without implementing the initialization logic in your constructor.

    The First one is an @PostConstruct where you define your configuration logic. Another option would be to let your ServiceClass implement the InitializingBean interface and put this configuration logic in your afterPropertiesSet method.