首页 > 其他 > 详细

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

时间:2015-07-01 12:27:32      阅读:208      评论:0      收藏:0      [点我收藏+]

为了演示下面的支持多参数的构造函数注入,我在这里写了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 学习(二)构造器注入(Constructor Inject)

原文:http://blog.csdn.net/u010834071/article/details/46706945

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!