Introduction to the difference between GoogleGuice and Spring frameworks in the ultra-lightweight DI container framework and the demo code snippets

Source: Internet
Author: User
It is not easy to be original. for details on the differences between GoogleGuice and Spring frameworks in the ultra-lightweight DI container framework and its demo code snippets, see DependencyInjection. Its role is natural.

It is not easy to be original. for details on the differences between the super-lightweight DI container framework Google Guice and Spring Framework and the demo code snippets

Code: http://www.zuidaima.com/share/1759689106541568.htm

Dependency Injection: DI (Dependency Injection). its role does not need to be discussed. DI containers, such as spring, picoContainer, and EJB containers, are mentioned. recently, google gave birth to a lighter DI container ...... Guice!
If you don't talk much about it, let's take a look at how Guice achieves injection.
Define a simple service interface and its implementation:


Package com. zuidaima. demo. guice;
Public interface MyService ...{
Void myMethod ();
}


Package com. zuidaima. demo. guice;
Public class MyServiceImpl implements MyService ...{
Public void myMethod ()...{
System. out. println ("Hello, World! ");
}
}

The above is the most common interface and its implementation, there is nothing to say.
Define a Test class, which includes a reference of the service object, which requires Guice to be injected


Package com. zuidaima. demo. guice;

Import com. google. inject. Inject;
Public class Client ...{
MyService service;
@ Inject // tell the container that the reference of the service object here needs to be injected.
Void setService (MyService service)... {// The method name can be defined at will
This. service = service;
}
Public void myMethod ()...{
Service. myMethod ();
}
}


There is no difference between @ Inject and Spring configuration. @ Inject indicates that the service needs to be injected to the container. when running, the container will take an instance to the service to complete the injection process.

The Module file defining Guice tells the container how to inject

Package com. zuidaima. demo. guice;


Import com. google. inject. Binder;
Import com. google. inject. Module;
Import com. google. inject. Scopes;


Public class MyModule implements Module ...{
Public void configure (Binder binder)... {binder. bind (MyService. class). to (MyServiceImpl. class). in (Scopes. SINGLETON );
// The code indicates that the MyServiceImpl object is dynamically assigned to the object defined by MyService during the runtime, and this object is a singleton object.
}
}
 


Create Test class

Package com. zuidaima. demo. guice;


Import com. google. inject. Guice;
Import com. google. inject. Injector;


Public class Test ...{


Public static void main (String [] args )...{
MyModule module = new MyModule (); // defines the injection rule
Injector injector = Guice. createInjector (module); // Generate the Injector according to the injection rules.
Client client = new Client ();
Injector. injectMembers (client); // The injector injects the bean to the client according to the rules.
Client. myMethod ();
}
}
 

Run the Test class. the console outputs: Hello, World!
Complete the injection process

Next, let's take a look at other usage features of Guice.
1. if you want to inject the object defined by MyService into MyServiceImpl instead of other implementation classes, you can add @ ImplementedBy (MyServiceImpl. class) to the MyService interface)

Package com. zuidaima. demo. guice;


Import com. google. inject. ImplementedBy;


@ ImplementedBy (MyServiceImpl. class)
// I always think this is a little different from the original intention of dependency injection?
Public interface MyService ...{
Void myMethod ();
}
 

Package com. zuidaima. demo. guice;


Import com. google. inject. ImplementedBy;


@ ImplementedBy (MyServiceImpl. class)
// I always think this is a little different from the original intention of dependency injection?
Public interface MyService ...{
Void myMethod ();
}
 

In this way, the container will be automatically injected to the MyServiceImpl object without adding anything in the configure method of MyModule.

2. annotation injection can be performed on the Field.
In Client. java, you can also mark this @ Inject in the front of MyService service; for example, @ Inject MyService service;


3. you can use custom Annotation annotations.



Package com. zuidaima. demo. guice;


Import java. lang. annotation. ElementType;
Import java. lang. annotation. Retention;
Import java. lang. annotation. RetentionPolicy;
Import java. lang. annotation. Target;


Import com. google. inject. BindingAnnotation;


@ Retention (RetentionPolicy. RUNTIME)
@ Target (... {ElementType. FIELD, ElementType. PARAMETER })
@ BindingAnnotation
Public @ interface MyInterface ...{
 
}
 

So the Client. java needs to be changed


Package com. zuidaima. demo. guice;


Import com. google. inject. Inject;


Public class Client ...{


@ Inject @ MyInterface MyService service;
 
Void setService (MyService service)... {// The method name can be defined at will
This. service = service;
}


Public void myMethod ()...{
Service. myMethod ();
}
}

The configure method in MyModule. java should be changed:

Binder. bind (MyService. class). annotatedWith (MyInterface. class). (
MyServiceImpl. class). in (Scopes. SINGLETON );
It means to inject the object defined by MyService marked as MyInterface

The Annotation member (Field, method, argument, etc.) for custom Annotation. this member has this attribute and can be running. according to the different attributes of these members, do something different? Such as AspectJ and xdoclet of spring.

Below is a comparison

Comparison between Guice and Spring
  Spring Guice
Use XML Isolate the relationship between classes to xml, and the container is responsible for injecting the called Object. Therefore, dependency injection is called. Without xml, the relationship between classes is isolated to the Module. the container injects the called object according to the description in the Module.
Use Annotation   Use
Supports custom Annotation annotations. for object references of the same interface definition, different custom Annotation annotations can be labeled for them to reference the same interface in the same class, different implementations are injected with annotations in the Module, which greatly increases flexibility.
The use of Annotation may not be a good thing, and new features such as the model may not be a good thing. Currently, most servers do not support jdk1.5, and wls is supported before 9, at present, the price of wls9 is rarely used by customers, at least none of the projects we have done. What are the functions that customers do not need?
Operation efficiency When loading the spring configuration file, xml needs to be parsed, with low efficiency and low getBean efficiency. However, the use environment does not involve getBean, and getBean is only used in the production environment, when loading spring applications, all injection has been completed, so this inefficiency is not a problem. When Annotation and cglib are used, the most obvious difference between high efficiency and spring is that spring completely injects all the injection points when loading the spring configuration file. what about Guice, it is injected during use, and the operation efficiency and flexibility are high.
Class coupling Low coupling, emphasizing non-intrusive classes, and processing dependencies in an external manner. the classes are clean and the dependencies on the classes are extremely low in the configuration file. High, code-level annotation, DI Mark @ inject intrude into the code, coupled to the class level, it's just an intrusion, the code is coupled with too many guice stuff, this greatly deviates from the original intention of dependency injection, which is detrimental to the maintainability and readability of the code.
When writing a class You need to write xml, configure Bean, and configure injection. You only need to declare it as @ inject, waiting for injection,
Finally, declare the injection method in the Unified Module.
Only supports IOC No, spring is already involved in many sections Yes. Currently, it is only a DI container.
Easy Code refactoring Unified xml configuration Portal, easy to change Configuration is performed in the Module, which is similar to spring.
Multiple injection modes are supported. Constructor, setter method Field, constructor, setter method
Flexibility  

1. if the reference of the same interface definition needs to be injected with different implementations, it is cumbersome to write different modules.

2. dynamic injection

If you want to inject an implementation, you still don't know. what should you do? spring cannot be written in the configuration file beforehand, and Guice can do it, that is to say, I don't know who to inject the object I want to inject. it is the implementation of this interface that can be obtained at runtime, which greatly improves the flexibility of dependency injection, dynamic injection.

Integration with existing frameworks 1. high. many existing excellent frameworks (such as struts1.x) provide spring integration portals, and spring is more than just dependency injection, including many aspects.
2. Spring also provides integration with Hibernate, which greatly simplifies development.
3. it provides a large number of interfaces for orm, rmi, and webservice.
1. it can be integrated with the existing framework. However, it is difficult to replace spring with a DI with a higher efficiency.
Configuration complexity It is difficult to locate the relationship between classes in xml. Locate the relationship between classes at the code level, which is more difficult

 

Let's talk about the difference between spring and guice with an ax example.
Let's take a look at the example of the next person (java object, caller) in different social forms that requires an Ax (java object, called:
(1) in the primitive society, there is basically no division of labor in the Labor society. people (Callers) who need an ax have to sharpen one by themselves, and each person has his own ax, if you change your stone axe to an iron axe, you need to learn how to sharpen it, which is extremely inefficient.
The corresponding situation in Java is: the caller in the java program creates a new called instance. High coupling, cumbersome modification and maintenance, and extremely low efficiency.
(2) in an industrial society, an ax is no longer done by ordinary people but produced by a factory. when people need an ax, they can buy an ax at the factory, there is no need to worry about how the ax is made. if the discarded iron ax is a steel ax, you only need to change the manufacturing process of the factory. The production process is determined by the factory, the workers have to use an ax.
The corresponding situation in Java is that the Java program caller can create a called in a simple factory and the change points are isolated in a simple factory. Although the coupling degree is reduced, the caller will be coupled with the factory, in addition, you need to locate your own factory.
(3) in modern industrial society, factories are booming. people only need to provide an ax Image. merchants will order your ax according to the image you provide and send it to the door.
Corresponding to the situation in Java: spring dependency injection
(4) enter the society allocated as needed, and the information enters modernization. people no longer go to the factory to buy an ax, and they no longer stick to what kind of ax is needed. they just need to make a phone call, describe what types of axes are needed. if you want to create an ax with high quality and low price, the seller will calculate the optimal production process based on the price of the parts on the market and create the most suitable one, more information, more humane.
Corresponding to the situation in Java: description-based injection, dynamic, flexible and simple injection, such as Guice.
 
I think Guice should be a benevolent and wise person, just like many forums where someone will discuss whether to learn Java or learn. net or the use of eclipse or Jbuilder is a boring topic, suitable for and meet the needs of the project, and can save labor and effort to complete the work, is the best.

You are welcome to discuss this with me.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.