1. Constant Injection method
Packagecom. Guice. Constantinjectdemo;Importcom. Google. Inject. Binder;Importcom. Google. Inject. Guice;Importcom. Google. Inject. Inject;Importcom. Google. Inject. Module;Importcom. Google. Inject. Name. Named;Importcom. Google. Inject. Name. Names;/ * * Bound constants * /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) {//values ABind to constant value a binder. Bindconstant(). Annotatedwith(Names. Named("a")). to( A);} }). getinstance(Constantinjectdemo. Class);System. out. println(Instance. A);//}}
In addition to the ability to bind int, other basic types can be bound in the Constantbindingbuilder class.
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. Attribute Injection method
Packagecom. Guice. Constantinjectdemo;Import Java. Util. Properties;Importcom. Google. Inject. Binder;Importcom. Google. Inject. Guice;Importcom. Google. Inject. Inject;Importcom. Google. Inject. Module;Importcom. Google. Inject. Name. Named;Importcom. Google. Inject. Name. Names;/** * TODO: Binding properties In addition to binding the basic type, you can also bind a properties to Guice, of course, because the properties are essentially a map<string,string> Therefore Guice also allows binding of a 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 Propertie s = new Properties ();Properties. SetProperty("CSDN","Www.csdn.com");Names. Bindproperties(Binder, properties);} }). getinstance(Propertiesinjectdemo. Class);System. out. println(Instance. Csdn);}}
Guice Learning (vii) constant and attribute injection (Constant and property Inject)