Source: http://www.cnblogs.com/whitewolf/p/4185908.html
Guice is an absolutely lightweight Java IOC container developed by Google Daniel Bob Lee. The advantage is:
- Faster, claiming to be 100 times times faster than spring.
- No external configuration (such as the need to use external can choose Guice Extension package), completely based on the annotation feature, support refactoring, code static check.
- Simple, fast, basic no learning costs.
Guice and spring have their own strengths, and Guice is better suited to embedded or high-performance but simple project scenarios such as OSGi containers, and spring is better suited for large project organizations.
Injection method
When we talk about the IOC framework, first of all our topics will be constructs, attributes, and function injection methods, and Guice implementations only need to label @inject on constructors, fields, or injected functions, such as:
Construction injection
public class OrderServiceImpl implements OrderService { private ItemService itemService; private PriceService priceService; @Inject public OrderServiceImpl(ItemService itemService, PriceService priceService) { this.itemService = itemService; this.priceService = priceService; } ...}
Attribute Injection
public class OrderServiceImpl implements OrderService { private ItemService itemService; private PriceService priceService; @Inject public void init(ItemService itemService, PriceService priceService) { this.itemService = itemService; this.priceService = priceService; } ...}
function (setter) injection
public class OrderServiceImpl implements OrderService { private ItemService itemService; private PriceService priceService; @Inject public void setItemService(ItemService itemService) { this.itemService = itemService; } @Inject public void setPriceService(PriceService priceService) { this.priceService = priceService; } ...}
Module Dependency Registration
Guice provides a dependency configuration class that needs to be inherited to Abstractmodule to implement the Configure method. In the Configure method we can configure dependencies with binder.
Binder uses chaining to form a unique set of semantic DSLs, such as:
- Basic configuration: Binder.bind (ServiceClass). to (Implclass). In (scopes.[ SINGLETON | No_scope]);
- No base class, interface configuration: Binder.bind (Implclass). In (scopes.[ SINGLETON | No_scope]);
- Service Instance configuration: Binder.bind (ServiceClass). ToInstance (Servieinstance). In (scopes.[ SINGLETON | No_scope]);
- Multiple instances are injected by name: Binder.bind (ServiceClass). Annotatedwith (names.named ("name")). (Implclass). In (scopes.[ SINGLETON | No_scope]);
- Runtime injection: Use the @provides annotation injection method, which is equivalent to the @bean of spring.
- @ImplementedBy: or label @implementedby on the implementation interface to specify its implementation class. This way is a bit anti-oo design, the abstract should not know its implementation class.
For the above configuration to be injected in a way that only requires @inject labeling, but for name injection requires adding @named annotations to the front of the parameter, such as:
public void configure() { final Binder binder = binder(); //TODO: bind named instance; binder.bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class); binder.bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);}@Injectpublic List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1, @Named("impl2") NamedService nameService2) {}
Guice can also use the @provides annotation injection method to run-time injection:
@Provides public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1, @Named("impl2") NamedService nameService2) { final ArrayList<NamedService> list = new ArrayList<NamedService>(); list.add(nameService1); list.add(nameService2); return list;}
Guice instances
The following is an example code for the Guice module: contains most of the common dependency configurations. See GitHub for more code.
Package com.github.greengerong.app;/** * *************************************** * * * * Auth:green Gerong * * date:2014 * * blog:http://greengerong.github.io/* * github:https://github.com/g Reengerong * * * * **************************************** */public class Appmodule extends Abstractmodule {private S Tatic final Logger Logger = Loggerfactory.getlogger (Appmodule.class); Private final Bundlecontext Bundlecontext; Public Appmodule (Bundlecontext bundlecontext) {this.bundlecontext = Bundlecontext; Logger.info (String.Format ("Enter app module with:%s", Bundlecontext)); } @Override public void Configure () {Final Binder binder = binder (); Todo:bind interface Binder.bind (Itemservice.class). to (Itemserviceimpl.class). in (SINGLETON); Binder.bind (Orderservice.class). to (Orderserviceimpl.class). in (SINGLETON); Todo:bind self class (without interface or base class) Binder.bind (Priceservice.class). in (Scopes.singleton); Todo:bind instance not class. Binder.bind (Runtimeservice.class). ToInstance (New Runtimeservice ()); Todo:bind named instance; Binder.bind (Namedservice.class). Annotatedwith (Names.named ("IMPL1")). to (Namedserviceimpl1.class); Binder.bind (Namedservice.class). Annotatedwith (Names.named ("ImpL2")). to (Namedserviceimpl2.class); } @Provides Public list<namedservice> getallitemservices (@Named ("Impl1") Namedservice NameService1, @Named ("ImpL2") Namedservice NameService2) {final arraylist<namedservice& Gt List = new arraylist<namedservice> (); List.add (NameService1); List.add (NAMESERVICE2); return list; }}
Use of Guice
The use of Guice is relatively straightforward, using Guice module initialization Guice to create its injector, such as:
Injector injector = Guice.createInjector(new AppModule(bundleContext));
Here you can pass in multiple module, we can use module separation domain dependency.
Guice API Method:
The Guice also supports different region configurations, the state overloads above, the State supports the Tool,development,production option, and the default is the development environment.
Subsequent
This article Guice a more complete demo code, see GitHub.
Guice also has many extensions such as AOP, the same service multiple instances inject SET,MAP,OSGI,UOW and other extensions, see Guice wiki.
Java Lightweight IOC Framework Guice (RPM)