Guice 学习(二)构造器注入(Constructor Inject)

为了演示下面的支持多参数的构造函数注入,我在这里写了2个接口和其实现类。注意事项写在了程序注释里面。

1、接口 (interface)
/*
 * Creation : 2015年6月30日
 */
package com.guice.constructorInject;

import com.google.inject.ImplementedBy;

@ImplementedBy(ServiceImpl.class)
public interface Service {
    public void execute();
}
/*
 * Creation : 2015年6月30日
 */
package com.guice.constructorInject;

import com.google.inject.ImplementedBy;

@ImplementedBy(HelloGuiceImpl.class)
public interface HelloGuice {
    public void sayHello();
}
2、实现类( implementation)
package com.guice.constructorInject;

public class ServiceImpl implements Service {
    @Override
    public void execute() {
        System.out.println("Hello Guice ,this is field inject demo !");

    }
}
package com.guice.constructorInject;

import com.google.inject.Singleton;

/*
 * 保证是单例
 */
@Singleton
public class HelloGuiceImpl implements HelloGuice {

    @Override
    public void sayHello() {
        System.out.println("Hello Guice !");

    }

}
3、测试类
/*
 * Creation : 2015年6月30日
 */
package com.guice.constructorInject;

import com.google.inject.Guice;
import com.google.inject.Inject;

public class ConstructorInjectDemo {
    private Service service;
    private HelloGuice helloGuice;

    public Service getService() {
        return service;
    }

    public HelloGuice getHelloGuice() {
        return helloGuice;
    }

    /**
     * 构造函数注入: 好处:可以保证只有一个地方来完成属性注入,
     * 可以确保在构造函数中完成一些初始化工作 不足:类的实例化与参数绑定了,限制了实例化类的方式。
     */
    /*
     * @Inject 
     * public ConstructorInjectDemo(Service service) { 
     *      this.service = service; 
     * }
     */

    /*
     * 支持多参数构造函数注入 ,但是必须只有一个构造函数上面标注Inject
     */
    @Inject
    public ConstructorInjectDemo(Service service, HelloGuice helloGuice) {
        this.service = service;
        this.helloGuice = helloGuice;
    }

    public static void main(String[] args) {
        ConstructorInjectDemo instance = Guice.createInjector().getInstance(ConstructorInjectDemo.class);
        instance.getService().execute();
        instance.getHelloGuice().sayHello();

    }

}

输出结果:

Hello Guice ,this is field inject demo !
Hello Guice !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值