I am writing a small application that implements select - insert operations in MongoDB .
There was a problem in initializing the database using the “initDB” method with the @PostConstruct annotation.
Session Bean Code:

package Library; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; @Stateless @Named public class BookSessionBean { @Inject Book book; private DBCollection bookCollection; /** * * @throws UnknownHostException */ @PostConstruct public void initDB() throws UnknownHostException { Mongo mongo = new Mongo(); DB db = mongo.getDB("booksDB"); bookCollection = db.getCollection("books"); if (bookCollection == null) { bookCollection = db.createCollection("books", null); } } public void createBook() { BasicDBObject doc = book.toDBObject(); bookCollection.insert(doc); } public List<Book> getBooks() { List<Book> books = new ArrayList<Book>(); DBCursor cursor = bookCollection.find(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); books.add(Book.fromDBObject(dbo)); } return books; } } 

The error itself:

The “initDB” method with the @PostConstruct annotation should not result in a raised exception being called

Screenshot

    1 answer 1

    In JavaDoc , javax.annotation.PostConstruct writes:

    Note: A PostConstruct interceptor method must not throw application exceptions

    You should remove throws UnknownHostException from the definition of the initDB() method. If any of the operations performed in the method require the handling of an UnknownHostException exception, then they should be executed in a try{...}catch(UnknownHostException){} .

    In the catch you can perform a choice of 2 actions:

    • Ignore an exception, for example, by simply listing the message in the log and continuing with the execution of the method In this case, the container will assume that the component is initialized correctly.
    • Wrap UnknownHostException in java.lang.RuntimeException and throw it away. In this case, the container will "understand" that the component is not initialized.