Java lightweight IOC framework Guice and iocguice

Source: Internet
Author: User

Java lightweight IOC framework Guice and iocguice

Guice is an absolutely lightweight java IoC container developed by Google Daniel Bob lee. Its advantages include:

Guice and spring have their own strengths. Guice is more suitable for embedded or high-performance but simple project solutions, such as OSGI containers, and spring is more suitable for large project organizations.

Injection Method

When talking about the IOC framework, we will first talk about the construction, attributes, and function injection methods. The implementation of Guice only needs to mark @ Inject on the constructor, field, or injection function, for example:

Constructor 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;    }    ...}
Property 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;    }    ...}
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 dependency configuration classes, which must be inherited to AbstractModule to implement the configure method. In the configure method, we can use Binder to configure dependencies.

The Binder uses the chain to form a set of unique semantic DSL, such:

  • Basic configuration: binder. bind (serviceClass). to (implClass). in (Scopes. [SINGLETON | NO_SCOPE]);
  • No base class or 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 ")). to (implClass ). in (Scopes. [SINGLETON | NO_SCOPE]);
  • Runtime injection: The @ Provides annotation injection method is equivalent to spring @ Bean.
  • @ ImplementedBy: Or Mark @ ImplementedBy on the implementation interface to specify its implementation class. This method is somewhat counter-OO design, so the abstract should not know its implementation class.

Only @ Inject annotation is required for the above configuration in the injection method, but @ Named annotation must be added before the parameter for name-based injection, for example:

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 for runtime injection: as shown in Figure

   @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 instance

The following is a Guice module instance code: contains most of the commonly used dependency configuration methods. For more code, see github.

package com.github.greengerong.app;/** * *************************************** * * * Auth: green gerong                     * * Date: 2014                             * * blog: http://greengerong.github.io/    * * github: https://github.com/greengerong * * * * **************************************** */public class AppModule extends AbstractModule {    private static 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> list = new ArrayList<NamedService>();        list.add(nameService1);        list.add(nameService2);        return list;    }}
Use of Guice

Guice is easy to use. You can use the Guice module to initialize Guice to create its injector, for example:

Injector injector = Guice.createInjector(new AppModule(bundleContext));

Multiple modules can be imported here. We can use modules to separate domain dependencies.

Guice api method:

public static Injector createInjector(Module... modules) public static Injector createInjector(Iterable<? extends Module> modules) public static Injector createInjector(Stage stage, Module... modules)public static Injector createInjector(Stage stage, Iterable<? extends Module> modules) 

Guice also supports different Region configurations. The State above is reloaded. The state supports TOOL, DEVELOPMENT, and PRODUCTION options. The default value is the DEVELOPMENT environment.

Follow-up

For more comprehensive demo code of Guice in this article, see github.

Guice also has many extensions, such as AOP. Multiple instances of the same service are injected with set, map, OSGI, and UOW extensions. For details, see Guice wiki.

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.