There is a boom in the Java community that uses lightweight containers to help assemble components from different projects and integrate into a cohesive application.
These underlying containers have a common pattern of demonstrating how they assemble components, and they propose a concept called "control reversal" (Inversion of controls).
Next we delve into how the pattern works in "Dependency Injection" (Dependency injection) and compares it to the service locator.
Components and Services
I mean, using components means that a lot of software can use it freely, without changing it, because the component is no longer under the control of the author.
Services are similar to components when used in external systems.
The only difference is that I expect to use the component locally (eg jar file,assembly,dll,or source inport).
The service is invoked remotely through a remote interface, and can be synchronous or asynchronous operations. (eg Web service, messaging system, RPC, or socket.)
Dependency Injection
Injector
It is divided into three types: constructor injection, setter injection and interface injection.
1 Constructors:
Class Movielister ...
Public movielister (Moviefinder Finder) {
This.finder = Finder;
}
2 setter:
Class Movielister ...
Private Moviefinder finder;
public void Setfinder (Moviefinder finder) {
This.finder = Finder;
}
The XML configuration of the setter
<beans>
<bean id= "Movielister" class= "spring. Movielister ">
<property name= "Finder" >
<ref local= "Moviefinder"/>
</property>
</bean>
</beans>
3 Interface:
Public interface Injectfinder {
void Injectfinder (Moviefinder finder);
}
Class Movielister implements Injectfinder
public void Injectfinder (Moviefinder finder) {
This.finder = Finder;
}
Service Locator
The main benefit of dependency injection is to remove dependencies on the implementation (implementations) of Movielister and Moviefinder. But this is not the only way, the other way is the service locator.
Class Servicelocator ...
private static Servicelocator soleinstance;
public static void Load (Servicelocator arg) {
Soleinstance = arg;
}
Private MAP Services = new HashMap ();
public static Object GetService (String key) {
return SoleInstance.services.get (key);
}
public void Loadservice (String key, Object service) {
Services.put (key, service);
}
Class Tester ...
private void Configure () {
Servicelocator locator = new Servicelocator ();
Locator.loadservice ("Moviefinder", New Colonmoviefinder ("Movies1.txt"));
Servicelocator.load (locator);
}
Class Movielister ...
Moviefinder finder = (moviefinder) servicelocator.getservice ("Moviefinder");
Dependency Injection is an alternative to service locator. The service locator has some advantages because of its direct behavior, but if you create classes in many applications, dependency injection is a better choice.
Thinking:
1.Service Locator vs Dependency Injection
2.Constructor versus Setter Injection
3.Code or configuration files
4.Separating Configuration from