2

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.

JavaLearner
  • 527
  • 1
  • 5
  • 16
  • 1
    just call `this()` as first line of your constructor or include the configuration code in the constructor you have. – Turing85 Aug 14 '20 at 10:47
  • Is it possible to have multiple constructors (inside service class) performing constructor injection? In that case calling `this()` inside every constructor would result into issues. – JavaLearner Aug 14 '20 at 10:53
  • 2
    "*Is it possible to have multiple constructors performing constructor injection?*" - By default, `@Service`s are singletons... – Turing85 Aug 14 '20 at 10:55
  • 1
    You can also use @PostConstruct in Spring – Cyril G. Aug 14 '20 at 11:12
  • Thank you @CyrilG. Using `PostConstruct` better suits my needs – JavaLearner Aug 15 '20 at 07:18

1 Answers1

1

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.

Daniel Jacob
  • 1,455
  • 9
  • 17
  • Thanks for mentioning InitializingBean. Any future reader may also want to read this https://stackoverflow.com/a/30726748/13866126 – JavaLearner Aug 15 '20 at 07:23