Wednesday, May 25, 2011

Initializing the bean by some init method using Spring

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.

  1. Using init-method attribute. This method is discussed here.
    Pros – doesn't require bean to implement an interface
  2. Implement InitializingBean
    Cons – more invasive than init-method approach
  3. 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

Chitika