Sometimes it required to call a (non-static) method in the bean only-once at the ApplicationContext load up, just to initialize the bean components. So you may inject some parameters by setters or constructors, but than you may have some other fields, which have to instantiated from those fields or separately like from some local file.
So for this various approaches are available. See here for these approaches.
- Using init-method attribute. This method is discussed here.
Pros – doesn't require bean to implement an interface - Implement InitializingBean
Cons – more invasive than init-method approach - Use JSR-250 @PostConstruct lifecycle annotation. This method is discussed here.
Pros :Useful when using component scanning to autodetect beans.
Makes it clear that a specific method is to be used for initialisation
Cons:
Initialisation no longer centrally specified in configuration. Now scattered throughout code.
No comments:
Post a Comment