javajakarta-eedesign-patternsjndiservice-locator

Is JNDI bad as service locator design pattern?


I'm a Java EE nooby developer, According to many resources on the internet which claim that service locator design pattern is an anti-pattern because it hides classes dependecies and more things and should be avoided as many as possbile and using Dependecy Injection instead, as we know JNDI is an implemantation of service locator pattern.

I googled to check that JNDI is an implementation of service locator and i found this response which claims this : Understanding JNDI

Althought i see that JNDI is used in Java EE application for many purposes (Datasources, EJB lookup ...), So should i use it or should i avoid it as more as possible?, if JNDI isn't bad then service locator isn't?


Solution

  • I think that the one part of your question, whether service locator is good or not or whether JNDI is about this pattern is a bit esoteric. I can give a general advice here as being a software architect for some years now, that a pattern by itself is not good and not bad, it is just a piece of solution that was successfully used before in many cases and thus be declared a pattern in order to be used for future cases which are similar. And another thing is, as opposed to many years ago, when one had to know the GoF book by heart in order to survive an interview, nowadays it is much more important to understand the underlying concepts of a framework like Java EE than to implement all those patterns, because what you have to implement is very often very simple and straightforward, but using them relies on those concepts.

    Concerning the second part of your question, you are almost never in need of directly using JNDI, but to use concepts built on top of it, as injection - that is what you should use in your application.