码迷,mamicode.com
首页 > 其他好文 > 详细

Guice 学习(七)常量和属性的注入( Constant and Property Inject)

时间:2015-07-01 12:16:50      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:guice   constant   property   inject   

1、常量注入方式

package com.guice.ConstantInjectDemo;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.name.Named;
import com.google.inject.name.Names;

/*
 *  绑定常量
 */
public class ConstantInjectDemo {
    @Inject
    @Named("a")
    private int a;

    public static void main(String[] args) {
        ConstantInjectDemo instance = Guice.createInjector(new Module() {

            @Override
            public void configure(Binder binder) {
                // 将数值22绑定到常量值a上
                binder.bindConstant().annotatedWith(Names.named("a")).to(22);

            }
        }).getInstance(ConstantInjectDemo.class);
        System.out.println(instance.a);// 22
    }
}

除了可以绑定int外,在ConstantBindingBuilder类中还可以绑定其它的基本类型。
com.google.inject.binder.ConstantBindingBuilder.to(String)
com.google.inject.binder.ConstantBindingBuilder.to(long)
com.google.inject.binder.ConstantBindingBuilder.to(boolean)
com.google.inject.binder.ConstantBindingBuilder.to(double)
com.google.inject.binder.ConstantBindingBuilder.to(float)
com.google.inject.binder.ConstantBindingBuilder.to(short)
com.google.inject.binder.ConstantBindingBuilder.to(char)

2、属性注入方式

package com.guice.ConstantInjectDemo;

import java.util.Properties;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.name.Named;
import com.google.inject.name.Names;

/**
 * TODO : 绑定Properties 除了可以绑定基本类型外,还可以绑定一个Properties到Guice中,当然了,由于Properties本质上时一个Map<String,String>, 因此Guice也允许绑定一个Map<String,String>。
 * 
 * @author E468380
 */
public class PropertiesInjectDemo {
    @Inject
    @Named("csdn")
    private String csdn;

    public static void main(String[] args) {
        PropertiesInjectDemo instance = Guice.createInjector(new Module() {

            @Override
            public void configure(Binder binder) {
                Properties properties = new Properties();
                properties.setProperty("csdn", "www.csdn.com");
                Names.bindProperties(binder, properties);
            }
        }).getInstance(PropertiesInjectDemo.class);
        System.out.println(instance.csdn);
    }
}

Guice 学习(七)常量和属性的注入( Constant and Property Inject)

标签:guice   constant   property   inject   

原文地址:http://blog.csdn.net/u010834071/article/details/46708105

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!