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 !

你可能感兴趣的:(Guice,注入,构造器)