Sunday, May 13, 2012

Spring annotation alternative for init-method attribute

Strangely, Spring natively does not provide an annotation support for the init-method attribute in xml. Consider a simple service:

import org.springframework.stereotype.Service;
public class BookServiceImpl implements BookService{
 
 public void init(){
  // init-method..
 }
 
 @Override
 public void buyBook() {
  //Implementation..
 }
}

The declaration for this service in a Spring context file would have been along these lines:
<bean name="bookService" class="org.bk.samples.types.BookServiceImpl" init-method="init"/>

the init-method contains the method name to be invoked post instantiation and after all the properties of the beans have been wired in.

The annotation equivalent of this is using @javax.annotation.PostConstruct annotation, which is part of the Common Annotations for Java.

So the equivalent annotation based annotation would be the following.

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService{
 
 @PostConstruct
 public void init(){
 }
 
 @Override
 public void buyBook() {
  //Implementation..
 }
}

1 comment:

  1. I believe that this may not be entirely true due to the ordering of Spring lifecycle events - PostConstruct is called from a Pre-Initialization BeanPostProcessor whereas the init-method and afterPropertiesSet() aren't (come between pre- and post-initialization). A useful nuiance if one is strugling with accessing the Application Context from within the @PostConstruct method and finding the injected/referenced collaborators have an annoyingly null application context.

    ReplyDelete