google guice入门

  • guice是google的一个轻量级的DI框架,下面上代码。
  • 首先是几个接口
public interface UserService {
	 void process();
}

public interface LogService {

	void log(String msg);
}

public interface Application {

	void work();
}
  • 对应的实现类
public class UserServiceImpl implements UserService{

	public void process() {
		
		System.out.println("do some service...");
	}
}

public class LogServiceImpl implements LogService{

	public void log(String msg) {
	
		System.out.println("log----" + msg);
	
	}
}
public class MyApp implements Application {
	//@Inject标识需要被注入的对象
    @Inject
    private UserService userService;
    @Inject
    private LogService logService;
    public void work() {
        userService.process();
        logService.log("server is running...");
    }
}
  • 接口和实现类的绑定
public class MyAppModule extends AbstractModule {
    /**
     * 配置接口和实现类之间的依赖关系
     */
    @Override
    protected void configure() {
        bind(LogService.class).to(LogServiceImpl.class);
        bind(UserService.class).to(UserServiceImpl.class);
        bind(Application.class).to(MyApp.class);
    }
}
  • 测试
public class MyAppTest extends TestCase {
    private static Injector injector;
    @BeforeClass
    protected void setUp() {
        injector = Guice.createInjector(new MyAppModule());
    }
    @Test
    public void testMyApp() {
        MyApp app = injector.getInstance(MyApp.class);
        app.work();
    }
}
  • 结果
do some service...
log----server is running...

你可能感兴趣的:(Java)