Google Guice 小试牛刀

  Google Guice是一个轻量级Dependency Injection依赖注入框架,能够提供动态注入,即当不知道注射的这个对象注射给谁呢,需要在运行时才能得到的的这个接口的实现,这是Spring DI所不具有的,Spring DI所有配置都是写死的,并且Spring DI在应用程序启动时所有依赖注入关系都会初始好,而Google Guice则可以根据需要进行依赖注入初始化,也就是说只有当需要时,就可以对依赖注入关系进行初始化。

 

  引入Google Guice包,从这个网址可以下载http://google-guice.googlecode.com/files/guice-3.0.zip

 

  一。CommentDao.java

 

package com.template.guice;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-8-2
 * Time: 下午9:37
 */
public interface CommentDao {

    public void comment(String message);
}

 

  二。CommentDaoImpl.java

 

package com.template.guice;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-8-2
 * Time: 下午9:38
 */
public class CommentDaoImpl implements CommentDao {

    public CommentDaoImpl() {
    }

    @Override
    public void comment(String message) {
        System.out.print(message);
    }
}

 

  三。CommentService.java

 

package com.template.guice;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-8-2
 * Time: 下午9:39
 */
public interface CommentService {

    public void comment();
}

 

  四。CommentServiceImpl.java

 

package com.template.guice;

import com.google.inject.Inject;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-8-2
 * Time: 下午9:39
 */
public class CommentServiceImpl implements CommentService {

    private CommentDao commentDao;

    @Inject
    public CommentServiceImpl(CommentDao commentDao) {
        this.commentDao = commentDao;
    }

    @Override
    public void comment() {
        commentDao.comment("This is a comment message!");
    }

    public void setCommentDao(CommentDao commentDao) {
        this.commentDao = commentDao;
    }
}

 

  五。CommentModule.java

 

package com.template.guice;

import com.google.inject.AbstractModule;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-8-2
 * Time: 下午9:46
 */
public class CommentModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(CommentDao.class).to(CommentDaoImpl.class);
    }
}
 

 

  六。Main.java

 

package com.template.guice;

import com.google.inject.Guice;
import com.google.inject.Injector;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-8-2
 * Time: 下午9:55
 */
public class Main {

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new CommentModule());
        CommentService commentService = injector.getInstance(CommentServiceImpl.class);
        commentService.comment();
    }
}

 

  @Inject表示Guice会隐式调用CommentServiceImpl的构造方法,而CommentModule则表示需要将CommentDao以CommentDaoImpl来注入对象中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值