Lucene using spring.

Today we are showing how to instantiate lucene using spring. We will be using annotations for instating the spring bean. Lets jump directly to the example class to see how it is done

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Component;

 * @author

public class SpringIndexManager {

 private static Logger logger = LogManager

 private String indexDirectory = "/opt/myapp/index";
 private FSDirectory directory;

 private IndexWriter writer;

 private SearcherManager searcherManager;

 public void init() {
  try {"index path :" + indexDirectory); = File(this.indexDirectory));
   this.writer = getIndexWriter(this.indexDirectory);
   this.searcherManager = new SearcherManager(writer, true, null);
  } catch (Exception e) {
   logger.error("error : " + this.indexDirectory, e);

 public void close() {"close writer");
  try {
   if (this.searcherManager != null) {
   }"SpringIndexManager shutdown done successfully!");
  } catch (CorruptIndexException e) {
   logger.error(e.getMessage(), e);
  } catch (IOException e) {
   logger.error(e.getMessage(), e);

 private IndexWriter getIndexWriter(String path) throws Exception {
  IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9, new StandardAnalyzer(Version.LUCENE_4_9));
  return new IndexWriter(, config);

 public void closeWriter() throws CorruptIndexException, IOException {
  if (this.writer != null) {


So the above class is a singleton spring bean.
The annotation PostConstruct on the method init make sure that lucene IndexWriter is started on the startup.
The annotation PreDestroy  makes sure that close method is called on shutdown.

You can use that class in your application as it is to start and stop lucene. I will soon be writing also about how to write and search text using lucene.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.