Core Components
- Service Locator: The single point of contact for the client. It abstracts the lookup logic and manages the cache.
- Initial Context: Creates the reference to the JNDI (Java Naming and Directory Interface) lookup. This is the expensive operation we want to avoid repeating.
- Cache: A simple map or list to store references to services that have already been found.
-
Service:
The actual concrete implementation (e.g.,
EJBService,JMSService) that the client wants to use.
Real-World Analogy
Think of a Phonebook (or Contact List):- You need to call a plumber (The Service).
- Without Locator: You call the operator (Initial Context) every single time, pay a fee, ask for the number, and then write it down. This is slow and expensive.
- With Locator:
- You call the operator once.
- You write the number in your personal Address Book (Cache).
- Next time you need the plumber, you just look in your book. You don’t call the operator again.
Implementation Example
Here is a raw Java implementation simulating the caching mechanism.1. Create the Service Interface
Service.java
2. Create Concrete Services
Service1.java
Service2.java
3. Create the Initial Context (Simulation)
This simulates the expensive JNDI lookup.InitialContext.java
4. Create the Cache
Cache.java
5. Create the Service Locator
This brings it all together.ServiceLocator.java
6. Demo Class
ServiceLocatorPatternDemo.java
When to Use
- Legacy Systems: If you are working with old EJB (Enterprise JavaBeans) systems where creating connections is very expensive.
- Registry: When you need a central registry to decouple clients from the concrete service implementations.
Pros & Cons
Spring Boot Context
Like the Business Delegate, the Service Locator pattern is considered an anti-pattern in modern Spring Boot development.Why? Dependency Injection (DI)
Service Locator asks: “Hey Locator, can you go find me the Service?” Dependency Injection says: “Here is the Service you need. I already found it for you.” In Spring, the ApplicationContext acts as the Cache and Locator, but it is invisible to your code. You simply declare what you need, and Spring provides it. Old Way (Service Locator):MyController.java
MyController.java
Spring Beans are Singleton by default, meaning they are cached automatically. You don’t need to write a custom
Cache class anymore.