Getting started with the guice framework and getting started with the guice framework
Guice framework is a framework similar to spring's ioc container. It is a simple and Lightweight Framework with extremely fast speed and high flexibility. Now I will write several guice programs first.
Here I will not provide the guice jar package, which can be easily downloaded.
Similar to spring, an interface and its implementation class must be provided before injection can be implemented. Program:
Interface HelloGuice:
package cn.com.guice;/** * Created by xiaxuan on 15/7/10. */public interface HelloGuice { public void sayHello();}
Implementation class:
package cn.com.guice.impl;import cn.com.guice.HelloGuice;/** * Created by xiaxuan on 15/7/10. */public class HelloGuiceImpl implements HelloGuice{ @Override public void sayHello() { System.out.println("Hello Guice!"); }}
Here we use a non-annotation form.
A module is used for injection and binding. The program is as follows:
package cn.com.guice;import cn.com.guice.impl.HelloGuiceImpl;import com.google.inject.Binder;import com.google.inject.Module;/** * Created by xiaxuan on 15/7/10. */public class HelloGuiceModule implements Module{ @Override public void configure(Binder binder) { binder.bind(HelloGuice.class).to(HelloGuiceImpl.class); }}
This basically completes the injection. Now we can test this program.
The test is as follows:
package cn.com.guice;import cn.com.guice.HelloGuice;import cn.com.guice.HelloGuiceModule;import com.google.inject.Guice;import com.google.inject.Injector;/** * Created by xiaxuan on 15/7/10. */public class TestGuice { public static void main(String[] args){ Injector injector= Guice.createInjector(new HelloGuiceModule()); HelloGuice helloGuice=injector.getInstance(HelloGuice.class); helloGuice.sayHello(); }}
Test results:
This completes di dependency injection.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.