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 java.io.File; import java.io.IOException; 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.search.SearcherManager; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.NIOFSDirectory; import org.apache.lucene.util.Version; import org.springframework.stereotype.Component; /** * * @author tutorial.author * */ @Component public class SpringIndexManager { private static Logger logger = LogManager .getLogger(SpringIndexManager.class); private String indexDirectory = "/opt/myapp/index"; private FSDirectory directory; private IndexWriter writer; private SearcherManager searcherManager; @PostConstruct public void init() { try { logger.info("index path :" + indexDirectory); this.directory = NIOFSDirectory.open(new File(this.indexDirectory)); this.writer = getIndexWriter(this.indexDirectory); this.searcherManager = new SearcherManager(writer, true, null); } catch (Exception e) { logger.error("error : " + this.indexDirectory, e); } } @PreDestroy public void close() { logger.info("close writer"); try { this.closeWriter(); if (this.searcherManager != null) { this.searcherManager.close(); } logger.info("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(this.directory, config); } public void closeWriter() throws CorruptIndexException, IOException { if (this.writer != null) { this.writer.close(); } } }
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.